From af5cd69f7b60c07c4830f2eca9b8b1544c7c4972 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Tue, 31 May 2022 21:08:56 +0200 Subject: set up gprc server --- planetwars-server/src/modules/bot_api.rs | 30 ++++++++++++++++++++++++++++++ planetwars-server/src/modules/mod.rs | 1 + 2 files changed, 31 insertions(+) create mode 100644 planetwars-server/src/modules/bot_api.rs (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs new file mode 100644 index 0000000..1941136 --- /dev/null +++ b/planetwars-server/src/modules/bot_api.rs @@ -0,0 +1,30 @@ +pub mod pb { + tonic::include_proto!("grpc.planetwars.bot_api"); +} + +use std::net::SocketAddr; + +use tonic; +use tonic::transport::Server; +use tonic::{Request, Response, Status}; + +pub struct BotApiServer {} + +#[tonic::async_trait] +impl pb::test_service_server::TestService for BotApiServer { + async fn greet(&self, req: Request) -> Result, Status> { + Ok(Response::new(pb::HelloResponse { + response: format!("hallo {}", req.get_ref().hello_message), + })) + } +} + +pub async fn run_bot_api() { + let server = BotApiServer {}; + let addr = SocketAddr::from(([127, 0, 0, 1], 50051)); + Server::builder() + .add_service(pb::test_service_server::TestServiceServer::new(server)) + .serve(addr) + .await + .unwrap() +} diff --git a/planetwars-server/src/modules/mod.rs b/planetwars-server/src/modules/mod.rs index bea28e0..43c2507 100644 --- a/planetwars-server/src/modules/mod.rs +++ b/planetwars-server/src/modules/mod.rs @@ -1,5 +1,6 @@ // This module implements general domain logic, not directly // tied to the database or API layers. +pub mod bot_api; pub mod bots; pub mod matches; pub mod ranking; -- cgit v1.2.3 From 90ecb13a1772dfdab20a006b421102c0aa584f60 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sun, 5 Jun 2022 21:22:38 +0200 Subject: baby steps towards a working bot api --- planetwars-server/src/modules/bot_api.rs | 150 ++++++++++++++++++++++++++++--- 1 file changed, 140 insertions(+), 10 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index 1941136..0f1ff82 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -3,27 +3,157 @@ pub mod pb { } use std::net::SocketAddr; +use std::ops::DerefMut; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use runner::match_context::{EventBus, PlayerHandle, RequestMessage}; +use runner::match_log::MatchLogger; +use tokio::sync::{mpsc, oneshot}; +use tokio_stream::wrappers::UnboundedReceiverStream; use tonic; use tonic::transport::Server; -use tonic::{Request, Response, Status}; +use tonic::{Request, Response, Status, Streaming}; -pub struct BotApiServer {} +use planetwars_matchrunner as runner; + +use crate::db; +use crate::{ConnectionPool, MAPS_DIR, MATCHES_DIR}; + +use super::matches::code_bundle_to_botspec; + +pub struct BotApiServer { + sync_thing: ServerSyncThing, +} + +#[tonic::async_trait] +impl pb::bot_api_service_server::BotApiService for BotApiServer { + type ConnectBotStream = UnboundedReceiverStream>; + + async fn connect_bot( + &self, + req: Request>, + ) -> Result, Status> { + println!("bot connected"); + let stream = req.into_inner(); + let sync_data = self.sync_thing.streams.lock().unwrap().take().unwrap(); + sync_data.tx.send(stream).unwrap(); + Ok(Response::new(UnboundedReceiverStream::new( + sync_data.server_messages, + ))) + } +} + +#[derive(Clone)] +struct ServerSyncThing { + streams: Arc>>, +} + +struct SyncThingData { + tx: oneshot::Sender>, + server_messages: mpsc::UnboundedReceiver>, +} + +impl ServerSyncThing { + fn new() -> Self { + ServerSyncThing { + streams: Arc::new(Mutex::new(None)), + } + } +} + +struct RemoteBotSpec { + sync_thing: ServerSyncThing, +} #[tonic::async_trait] -impl pb::test_service_server::TestService for BotApiServer { - async fn greet(&self, req: Request) -> Result, Status> { - Ok(Response::new(pb::HelloResponse { - response: format!("hallo {}", req.get_ref().hello_message), - })) +impl runner::BotSpec for RemoteBotSpec { + async fn run_bot( + &self, + player_id: u32, + event_bus: Arc>, + _match_logger: MatchLogger, + ) -> Box { + let (tx, rx) = oneshot::channel(); + let (server_msg_snd, server_msg_recv) = mpsc::unbounded_channel(); + *self.sync_thing.streams.lock().unwrap().deref_mut() = Some(SyncThingData { + tx, + server_messages: server_msg_recv, + }); + + let client_messages = rx.await.unwrap(); + tokio::spawn(handle_bot_messages(player_id, event_bus, client_messages)); + + Box::new(RemoteBotHandle { + sender: server_msg_snd, + }) + } +} + +async fn handle_bot_messages( + player_id: u32, + event_bus: Arc>, + mut messages: Streaming, +) { + while let Some(message) = messages.message().await.unwrap() { + let request_id = (player_id, message.request_id as u32); + event_bus + .lock() + .unwrap() + .resolve_request(request_id, Ok(message.content)); + } +} + +struct RemoteBotHandle { + sender: mpsc::UnboundedSender>, +} + +impl PlayerHandle for RemoteBotHandle { + fn send_request(&mut self, r: RequestMessage) { + self.sender + .send(Ok(pb::PlayerRequest { + request_id: r.request_id as i32, + content: r.content, + })) + .unwrap(); } } -pub async fn run_bot_api() { - let server = BotApiServer {}; +async fn run_match(sync_thing: ServerSyncThing, pool: ConnectionPool) { + let conn = pool.get().await.unwrap(); + + let opponent = db::bots::find_bot_by_name("simplebot", &conn).unwrap(); + let opponent_code_bundle = db::bots::active_code_bundle(opponent.id, &conn).unwrap(); + + let log_file_name = "remote_match.log"; + + let remote_bot_spec = RemoteBotSpec { sync_thing }; + + let match_config = runner::MatchConfig { + map_path: PathBuf::from(MAPS_DIR).join("hex.json"), + map_name: "hex".to_string(), + log_path: PathBuf::from(MATCHES_DIR).join(&log_file_name), + players: vec![ + runner::MatchPlayer { + bot_spec: Box::new(remote_bot_spec), + }, + runner::MatchPlayer { + bot_spec: code_bundle_to_botspec(&opponent_code_bundle), + }, + ], + }; + + runner::run_match(match_config).await; +} + +pub async fn run_bot_api(pool: ConnectionPool) { + let sync_thing = ServerSyncThing::new(); + tokio::spawn(run_match(sync_thing.clone(), pool)); + let server = BotApiServer { sync_thing }; + let addr = SocketAddr::from(([127, 0, 0, 1], 50051)); Server::builder() - .add_service(pb::test_service_server::TestServiceServer::new(server)) + .add_service(pb::bot_api_service_server::BotApiServiceServer::new(server)) .serve(addr) .await .unwrap() -- cgit v1.2.3 From d0faec7d1f4deb132554db7f946df4b9d4e9711b Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Mon, 6 Jun 2022 13:08:43 +0200 Subject: implement PlayerRouter --- planetwars-server/src/modules/bot_api.rs | 71 ++++++++++++++++++++------------ 1 file changed, 45 insertions(+), 26 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index 0f1ff82..2face62 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -2,8 +2,8 @@ pub mod pb { tonic::include_proto!("grpc.planetwars.bot_api"); } +use std::collections::HashMap; use std::net::SocketAddr; -use std::ops::DerefMut; use std::path::PathBuf; use std::sync::{Arc, Mutex}; @@ -23,7 +23,35 @@ use crate::{ConnectionPool, MAPS_DIR, MATCHES_DIR}; use super::matches::code_bundle_to_botspec; pub struct BotApiServer { - sync_thing: ServerSyncThing, + router: PlayerRouter, +} + +/// Routes players to their handler +#[derive(Clone)] +struct PlayerRouter { + routing_table: Arc>>, +} + +impl PlayerRouter { + pub fn new() -> Self { + PlayerRouter { + routing_table: Arc::new(Mutex::new(HashMap::new())), + } + } +} + +// TODO: implement a way to expire entries +impl PlayerRouter { + fn put(&self, player_id: String, entry: SyncThingData) { + let mut routing_table = self.routing_table.lock().unwrap(); + routing_table.insert(player_id, entry); + } + + fn get(&self, player_id: &str) -> Option { + // TODO: this design does not allow for reconnects. Is this desired? + let mut routing_table = self.routing_table.lock().unwrap(); + routing_table.remove(player_id) + } } #[tonic::async_trait] @@ -36,7 +64,8 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { ) -> Result, Status> { println!("bot connected"); let stream = req.into_inner(); - let sync_data = self.sync_thing.streams.lock().unwrap().take().unwrap(); + // TODO: return error when player does not exist + let sync_data = self.router.get("test_player").unwrap(); sync_data.tx.send(stream).unwrap(); Ok(Response::new(UnboundedReceiverStream::new( sync_data.server_messages, @@ -44,26 +73,13 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { } } -#[derive(Clone)] -struct ServerSyncThing { - streams: Arc>>, -} - struct SyncThingData { tx: oneshot::Sender>, server_messages: mpsc::UnboundedReceiver>, } -impl ServerSyncThing { - fn new() -> Self { - ServerSyncThing { - streams: Arc::new(Mutex::new(None)), - } - } -} - struct RemoteBotSpec { - sync_thing: ServerSyncThing, + router: PlayerRouter, } #[tonic::async_trait] @@ -76,10 +92,13 @@ impl runner::BotSpec for RemoteBotSpec { ) -> Box { let (tx, rx) = oneshot::channel(); let (server_msg_snd, server_msg_recv) = mpsc::unbounded_channel(); - *self.sync_thing.streams.lock().unwrap().deref_mut() = Some(SyncThingData { - tx, - server_messages: server_msg_recv, - }); + self.router.put( + "test_player".to_string(), + SyncThingData { + tx, + server_messages: server_msg_recv, + }, + ); let client_messages = rx.await.unwrap(); tokio::spawn(handle_bot_messages(player_id, event_bus, client_messages)); @@ -119,7 +138,7 @@ impl PlayerHandle for RemoteBotHandle { } } -async fn run_match(sync_thing: ServerSyncThing, pool: ConnectionPool) { +async fn run_match(router: PlayerRouter, pool: ConnectionPool) { let conn = pool.get().await.unwrap(); let opponent = db::bots::find_bot_by_name("simplebot", &conn).unwrap(); @@ -127,7 +146,7 @@ async fn run_match(sync_thing: ServerSyncThing, pool: ConnectionPool) { let log_file_name = "remote_match.log"; - let remote_bot_spec = RemoteBotSpec { sync_thing }; + let remote_bot_spec = RemoteBotSpec { router }; let match_config = runner::MatchConfig { map_path: PathBuf::from(MAPS_DIR).join("hex.json"), @@ -147,9 +166,9 @@ async fn run_match(sync_thing: ServerSyncThing, pool: ConnectionPool) { } pub async fn run_bot_api(pool: ConnectionPool) { - let sync_thing = ServerSyncThing::new(); - tokio::spawn(run_match(sync_thing.clone(), pool)); - let server = BotApiServer { sync_thing }; + let router = PlayerRouter::new(); + tokio::spawn(run_match(router.clone(), pool)); + let server = BotApiServer { router }; let addr = SocketAddr::from(([127, 0, 0, 1], 50051)); Server::builder() -- cgit v1.2.3 From 2f915af91982073644be94bb2c68e095ffd35596 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Mon, 6 Jun 2022 14:25:56 +0200 Subject: send player_id through request metadata --- planetwars-server/src/modules/bot_api.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index 2face62..f6e4d5c 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -62,10 +62,23 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { &self, req: Request>, ) -> Result, Status> { - println!("bot connected"); + // TODO: clean up errors + let player_id = req + .metadata() + .get("player_id") + .ok_or_else(|| Status::unauthenticated("no player_id provided"))?; + + let player_id_str = player_id + .to_str() + .map_err(|_| Status::invalid_argument("unreadable string"))?; + + let sync_data = self + .router + .get(player_id_str) + .ok_or_else(|| Status::not_found("player_id not found"))?; + let stream = req.into_inner(); - // TODO: return error when player does not exist - let sync_data = self.router.get("test_player").unwrap(); + sync_data.tx.send(stream).unwrap(); Ok(Response::new(UnboundedReceiverStream::new( sync_data.server_messages, -- cgit v1.2.3 From 69421d7b25090724eaa9399f83f83ca36deab882 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Mon, 6 Jun 2022 20:23:01 +0200 Subject: bot api: handle timeouts and disconnects --- planetwars-server/src/modules/bot_api.rs | 63 ++++++++++++++++++++++++++++---- 1 file changed, 55 insertions(+), 8 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index f6e4d5c..f5aae20 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -6,8 +6,9 @@ use std::collections::HashMap; use std::net::SocketAddr; use std::path::PathBuf; use std::sync::{Arc, Mutex}; +use std::time::Duration; -use runner::match_context::{EventBus, PlayerHandle, RequestMessage}; +use runner::match_context::{EventBus, PlayerHandle, RequestError, RequestMessage}; use runner::match_log::MatchLogger; use tokio::sync::{mpsc, oneshot}; use tokio_stream::wrappers::UnboundedReceiverStream; @@ -114,10 +115,16 @@ impl runner::BotSpec for RemoteBotSpec { ); let client_messages = rx.await.unwrap(); - tokio::spawn(handle_bot_messages(player_id, event_bus, client_messages)); + tokio::spawn(handle_bot_messages( + player_id, + event_bus.clone(), + client_messages, + )); Box::new(RemoteBotHandle { sender: server_msg_snd, + player_id, + event_bus, }) } } @@ -138,19 +145,59 @@ async fn handle_bot_messages( struct RemoteBotHandle { sender: mpsc::UnboundedSender>, + player_id: u32, + event_bus: Arc>, } impl PlayerHandle for RemoteBotHandle { fn send_request(&mut self, r: RequestMessage) { - self.sender - .send(Ok(pb::PlayerRequest { - request_id: r.request_id as i32, - content: r.content, - })) - .unwrap(); + let res = self.sender.send(Ok(pb::PlayerRequest { + request_id: r.request_id as i32, + content: r.content, + })); + match res { + Ok(()) => { + // schedule a timeout. See comments at method implementation + tokio::spawn(schedule_timeout( + (self.player_id, r.request_id), + r.timeout, + self.event_bus.clone(), + )); + } + Err(_send_error) => { + // cannot contact the remote bot anymore; + // directly mark all requests as timed out. + // TODO: create a dedicated error type for this. + // should it be logged? + self.event_bus + .lock() + .unwrap() + .resolve_request((self.player_id, r.request_id), Err(RequestError::Timeout)); + } + } } } +// TODO: this will spawn a task for every request, which might not be ideal. +// Some alternatives: +// - create a single task that manages all time-outs. +// - intersperse timeouts with incoming client messages +// - push timeouts upwards, into the matchrunner logic (before we hit the playerhandle). +// This was initially not done to allow timer start to be delayed until the message actually arrived +// with the player. Is this still needed, or is there a different way to do this? +// +async fn schedule_timeout( + request_id: (u32, u32), + duration: Duration, + event_bus: Arc>, +) { + tokio::time::sleep(duration).await; + event_bus + .lock() + .unwrap() + .resolve_request(request_id, Err(RequestError::Timeout)); +} + async fn run_match(router: PlayerRouter, pool: ConnectionPool) { let conn = pool.get().await.unwrap(); -- cgit v1.2.3 From ff061f2a7a0e3a62792ffcef8f2cd3ec6ddc5710 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Tue, 7 Jun 2022 19:12:49 +0200 Subject: timeout when player never connects --- planetwars-server/src/modules/bot_api.rs | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index f5aae20..2fffc79 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -48,7 +48,7 @@ impl PlayerRouter { routing_table.insert(player_id, entry); } - fn get(&self, player_id: &str) -> Option { + fn take(&self, player_id: &str) -> Option { // TODO: this design does not allow for reconnects. Is this desired? let mut routing_table = self.routing_table.lock().unwrap(); routing_table.remove(player_id) @@ -75,7 +75,7 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { let sync_data = self .router - .get(player_id_str) + .take(player_id_str) .ok_or_else(|| Status::not_found("player_id not found"))?; let stream = req.into_inner(); @@ -106,21 +106,35 @@ impl runner::BotSpec for RemoteBotSpec { ) -> Box { let (tx, rx) = oneshot::channel(); let (server_msg_snd, server_msg_recv) = mpsc::unbounded_channel(); + let player_key = "test_player".to_string(); self.router.put( - "test_player".to_string(), + player_key.clone(), SyncThingData { tx, server_messages: server_msg_recv, }, ); - let client_messages = rx.await.unwrap(); - tokio::spawn(handle_bot_messages( - player_id, - event_bus.clone(), - client_messages, - )); + let fut = tokio::time::timeout(Duration::from_secs(10), rx); + match fut.await { + Ok(Ok(client_messages)) => { + // let client_messages = rx.await.unwrap(); + tokio::spawn(handle_bot_messages( + player_id, + event_bus.clone(), + client_messages, + )); + } + _ => { + // ensure router cleanup + self.router.take(&player_key); + } + }; + // If the player did not connect, the receiving half of `sender` + // will be dropped here, resulting in a time-out for every turn. + // This is fine for now, but + // TODO: provide a formal mechanism for player startup failure Box::new(RemoteBotHandle { sender: server_msg_snd, player_id, -- cgit v1.2.3 From 1b2472fbfc876c3f8b6cf5dd6164308123fed133 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Wed, 8 Jun 2022 22:37:38 +0200 Subject: implement grpc match creation PoC --- planetwars-server/src/modules/bot_api.rs | 86 ++++++++++++++++++++------------ 1 file changed, 54 insertions(+), 32 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index 2fffc79..8aa5d29 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -19,11 +19,13 @@ use tonic::{Request, Response, Status, Streaming}; use planetwars_matchrunner as runner; use crate::db; +use crate::util::gen_alphanumeric; use crate::{ConnectionPool, MAPS_DIR, MATCHES_DIR}; use super::matches::code_bundle_to_botspec; pub struct BotApiServer { + conn_pool: ConnectionPool, router: PlayerRouter, } @@ -85,6 +87,50 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { sync_data.server_messages, ))) } + + async fn create_match( + &self, + req: Request, + ) -> Result, Status> { + // TODO: unify with matchrunner module + let conn = self.conn_pool.get().await.unwrap(); + + let match_request = req.get_ref(); + + let opponent = db::bots::find_bot_by_name(&match_request.opponent_name, &conn) + .map_err(|_| Status::not_found("opponent not found"))?; + let opponent_code_bundle = db::bots::active_code_bundle(opponent.id, &conn) + .map_err(|_| Status::not_found("opponent has no code"))?; + + let log_file_name = "remote_match.log"; + let player_key = gen_alphanumeric(32); + + let remote_bot_spec = RemoteBotSpec { + player_key: player_key.clone(), + router: self.router.clone(), + }; + + let match_config = runner::MatchConfig { + map_path: PathBuf::from(MAPS_DIR).join("hex.json"), + map_name: "hex".to_string(), + log_path: PathBuf::from(MATCHES_DIR).join(&log_file_name), + players: vec![ + runner::MatchPlayer { + bot_spec: Box::new(remote_bot_spec), + }, + runner::MatchPlayer { + bot_spec: code_bundle_to_botspec(&opponent_code_bundle), + }, + ], + }; + + tokio::spawn(runner::run_match(match_config)); + Ok(Response::new(pb::CreatedMatch { + // TODO + match_id: 0, + player_key, + })) + } } struct SyncThingData { @@ -93,6 +139,7 @@ struct SyncThingData { } struct RemoteBotSpec { + player_key: String, router: PlayerRouter, } @@ -106,9 +153,8 @@ impl runner::BotSpec for RemoteBotSpec { ) -> Box { let (tx, rx) = oneshot::channel(); let (server_msg_snd, server_msg_recv) = mpsc::unbounded_channel(); - let player_key = "test_player".to_string(); self.router.put( - player_key.clone(), + self.player_key.clone(), SyncThingData { tx, server_messages: server_msg_recv, @@ -127,7 +173,7 @@ impl runner::BotSpec for RemoteBotSpec { } _ => { // ensure router cleanup - self.router.take(&player_key); + self.router.take(&self.player_key); } }; @@ -183,6 +229,7 @@ impl PlayerHandle for RemoteBotHandle { // directly mark all requests as timed out. // TODO: create a dedicated error type for this. // should it be logged? + println!("send error: {:?}", _send_error); self.event_bus .lock() .unwrap() @@ -212,37 +259,12 @@ async fn schedule_timeout( .resolve_request(request_id, Err(RequestError::Timeout)); } -async fn run_match(router: PlayerRouter, pool: ConnectionPool) { - let conn = pool.get().await.unwrap(); - - let opponent = db::bots::find_bot_by_name("simplebot", &conn).unwrap(); - let opponent_code_bundle = db::bots::active_code_bundle(opponent.id, &conn).unwrap(); - - let log_file_name = "remote_match.log"; - - let remote_bot_spec = RemoteBotSpec { router }; - - let match_config = runner::MatchConfig { - map_path: PathBuf::from(MAPS_DIR).join("hex.json"), - map_name: "hex".to_string(), - log_path: PathBuf::from(MATCHES_DIR).join(&log_file_name), - players: vec![ - runner::MatchPlayer { - bot_spec: Box::new(remote_bot_spec), - }, - runner::MatchPlayer { - bot_spec: code_bundle_to_botspec(&opponent_code_bundle), - }, - ], - }; - - runner::run_match(match_config).await; -} - pub async fn run_bot_api(pool: ConnectionPool) { let router = PlayerRouter::new(); - tokio::spawn(run_match(router.clone(), pool)); - let server = BotApiServer { router }; + let server = BotApiServer { + router, + conn_pool: pool.clone(), + }; let addr = SocketAddr::from(([127, 0, 0, 1], 50051)); Server::builder() -- cgit v1.2.3 From d1977b95c82f608bc558432cdfba8026aaf0648d Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Thu, 9 Jun 2022 20:57:45 +0200 Subject: consistently use player_key and player_id --- planetwars-server/src/modules/bot_api.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index 8aa5d29..4eb13c1 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -45,15 +45,15 @@ impl PlayerRouter { // TODO: implement a way to expire entries impl PlayerRouter { - fn put(&self, player_id: String, entry: SyncThingData) { + fn put(&self, player_key: String, entry: SyncThingData) { let mut routing_table = self.routing_table.lock().unwrap(); - routing_table.insert(player_id, entry); + routing_table.insert(player_key, entry); } - fn take(&self, player_id: &str) -> Option { + fn take(&self, player_key: &str) -> Option { // TODO: this design does not allow for reconnects. Is this desired? let mut routing_table = self.routing_table.lock().unwrap(); - routing_table.remove(player_id) + routing_table.remove(player_key) } } @@ -66,19 +66,19 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { req: Request>, ) -> Result, Status> { // TODO: clean up errors - let player_id = req + let player_key = req .metadata() - .get("player_id") - .ok_or_else(|| Status::unauthenticated("no player_id provided"))?; + .get("player_key") + .ok_or_else(|| Status::unauthenticated("no player_key provided"))?; - let player_id_str = player_id + let player_key_str = player_key .to_str() .map_err(|_| Status::invalid_argument("unreadable string"))?; let sync_data = self .router - .take(player_id_str) - .ok_or_else(|| Status::not_found("player_id not found"))?; + .take(player_key_str) + .ok_or_else(|| Status::not_found("player_key not found"))?; let stream = req.into_inner(); -- cgit v1.2.3 From a3766980735851e9aa4b56a80e91c0b77cf63adb Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Fri, 10 Jun 2022 21:49:32 +0200 Subject: update RunMatch helper to allow for remote bots --- planetwars-server/src/modules/matches.rs | 50 +++++++++++++++++++++++--------- planetwars-server/src/modules/ranking.rs | 9 ++++-- 2 files changed, 42 insertions(+), 17 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/matches.rs b/planetwars-server/src/modules/matches.rs index a254bac..6d9261d 100644 --- a/planetwars-server/src/modules/matches.rs +++ b/planetwars-server/src/modules/matches.rs @@ -16,32 +16,54 @@ use crate::{ const PYTHON_IMAGE: &str = "python:3.10-slim-buster"; -pub struct RunMatch<'a> { +pub struct RunMatch { log_file_name: String, - player_code_bundles: Vec<&'a db::bots::CodeBundle>, + players: Vec, match_id: Option, } -impl<'a> RunMatch<'a> { - pub fn from_players(player_code_bundles: Vec<&'a db::bots::CodeBundle>) -> Self { +pub struct MatchPlayer { + bot_spec: Box, + // meta that will be passed on to database + code_bundle_id: Option, +} + +impl MatchPlayer { + pub fn from_code_bundle(code_bundle: &db::bots::CodeBundle) -> Self { + MatchPlayer { + bot_spec: code_bundle_to_botspec(code_bundle), + code_bundle_id: Some(code_bundle.id), + } + } + + pub fn from_bot_spec(bot_spec: Box) -> Self { + MatchPlayer { + bot_spec, + code_bundle_id: None, + } + } +} + +impl RunMatch { + pub fn from_players(players: Vec) -> Self { let log_file_name = format!("{}.log", gen_alphanumeric(16)); RunMatch { log_file_name, - player_code_bundles, + players, match_id: None, } } - pub fn runner_config(&self) -> runner::MatchConfig { + pub fn into_runner_config(self) -> runner::MatchConfig { runner::MatchConfig { map_path: PathBuf::from(MAPS_DIR).join("hex.json"), map_name: "hex".to_string(), log_path: PathBuf::from(MATCHES_DIR).join(&self.log_file_name), players: self - .player_code_bundles - .iter() - .map(|b| runner::MatchPlayer { - bot_spec: code_bundle_to_botspec(b), + .players + .into_iter() + .map(|player| runner::MatchPlayer { + bot_spec: player.bot_spec, }) .collect(), } @@ -56,10 +78,10 @@ impl<'a> RunMatch<'a> { log_path: &self.log_file_name, }; let new_match_players = self - .player_code_bundles + .players .iter() - .map(|b| db::matches::MatchPlayerData { - code_bundle_id: b.id, + .map(|p| db::matches::MatchPlayerData { + code_bundle_id: p.code_bundle_id, }) .collect::>(); @@ -70,7 +92,7 @@ impl<'a> RunMatch<'a> { pub fn spawn(self, pool: ConnectionPool) -> JoinHandle { let match_id = self.match_id.expect("match must be saved before running"); - let runner_config = self.runner_config(); + let runner_config = self.into_runner_config(); tokio::spawn(run_match_task(pool, runner_config, match_id)) } } diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs index f76fbae..d83debb 100644 --- a/planetwars-server/src/modules/ranking.rs +++ b/planetwars-server/src/modules/ranking.rs @@ -1,7 +1,7 @@ use crate::{db::bots::Bot, DbPool}; use crate::db; -use crate::modules::matches::RunMatch; +use crate::modules::matches::{MatchPlayer, RunMatch}; use rand::seq::SliceRandom; use std::time::Duration; use tokio; @@ -43,9 +43,12 @@ async fn play_ranking_match(selected_bots: Vec, db_pool: DbPool) { code_bundles.push(code_bundle); } - let code_bundle_refs = code_bundles.iter().map(|b| b).collect::>(); + let players = code_bundles + .iter() + .map(MatchPlayer::from_code_bundle) + .collect::>(); - let mut run_match = RunMatch::from_players(code_bundle_refs); + let mut run_match = RunMatch::from_players(players); run_match .store_in_database(&db_conn) .expect("could not store match in db"); -- cgit v1.2.3 From 7a3b801f58752a78b65e3e7e7b998b6479f980f7 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sat, 11 Jun 2022 17:50:44 +0200 Subject: use RunMatch in bot_api service --- planetwars-server/src/modules/bot_api.rs | 43 +++++++++++++++----------------- 1 file changed, 20 insertions(+), 23 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index 4eb13c1..0ecbf71 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -4,7 +4,6 @@ pub mod pb { use std::collections::HashMap; use std::net::SocketAddr; -use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -20,9 +19,9 @@ use planetwars_matchrunner as runner; use crate::db; use crate::util::gen_alphanumeric; -use crate::{ConnectionPool, MAPS_DIR, MATCHES_DIR}; +use crate::ConnectionPool; -use super::matches::code_bundle_to_botspec; +use super::matches::{MatchPlayer, RunMatch}; pub struct BotApiServer { conn_pool: ConnectionPool, @@ -43,6 +42,12 @@ impl PlayerRouter { } } +impl Default for PlayerRouter { + fn default() -> Self { + Self::new() + } +} + // TODO: implement a way to expire entries impl PlayerRouter { fn put(&self, player_key: String, entry: SyncThingData) { @@ -102,37 +107,29 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { let opponent_code_bundle = db::bots::active_code_bundle(opponent.id, &conn) .map_err(|_| Status::not_found("opponent has no code"))?; - let log_file_name = "remote_match.log"; let player_key = gen_alphanumeric(32); - let remote_bot_spec = RemoteBotSpec { + let remote_bot_spec = Box::new(RemoteBotSpec { player_key: player_key.clone(), router: self.router.clone(), - }; - - let match_config = runner::MatchConfig { - map_path: PathBuf::from(MAPS_DIR).join("hex.json"), - map_name: "hex".to_string(), - log_path: PathBuf::from(MATCHES_DIR).join(&log_file_name), - players: vec![ - runner::MatchPlayer { - bot_spec: Box::new(remote_bot_spec), - }, - runner::MatchPlayer { - bot_spec: code_bundle_to_botspec(&opponent_code_bundle), - }, - ], - }; + }); + let mut run_match = RunMatch::from_players(vec![ + MatchPlayer::from_bot_spec(remote_bot_spec), + MatchPlayer::from_code_bundle(&opponent_code_bundle), + ]); + let created_match = run_match + .store_in_database(&conn) + .expect("failed to save match"); + run_match.spawn(self.conn_pool.clone()); - tokio::spawn(runner::run_match(match_config)); Ok(Response::new(pb::CreatedMatch { - // TODO - match_id: 0, + match_id: created_match.base.id, player_key, })) } } +// TODO: please rename me struct SyncThingData { tx: oneshot::Sender>, server_messages: mpsc::UnboundedReceiver>, -- cgit v1.2.3 From dde0bc820e47a372c9b1042249637c708a323188 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sun, 12 Jun 2022 21:03:41 +0200 Subject: accept docker push --- planetwars-server/src/modules/mod.rs | 1 + planetwars-server/src/modules/registry.rs | 215 ++++++++++++++++++++++++++++++ 2 files changed, 216 insertions(+) create mode 100644 planetwars-server/src/modules/registry.rs (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/mod.rs b/planetwars-server/src/modules/mod.rs index bea28e0..d66f568 100644 --- a/planetwars-server/src/modules/mod.rs +++ b/planetwars-server/src/modules/mod.rs @@ -3,3 +3,4 @@ pub mod bots; pub mod matches; pub mod ranking; +pub mod registry; diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs new file mode 100644 index 0000000..d63621a --- /dev/null +++ b/planetwars-server/src/modules/registry.rs @@ -0,0 +1,215 @@ +use axum::body::Body; +use axum::extract::{BodyStream, Path, Query}; +use axum::handler::Handler; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, head, post, put}; +use axum::Router; +use hyper::StatusCode; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::path::PathBuf; +use tokio::io::AsyncWriteExt; + +use crate::util::gen_alphanumeric; + +const REGISTRY_PATH: &'static str = "./data/registry"; +pub fn registry_service() -> Router { + Router::new() + .nest("/v2", registry_api_v2()) + .fallback(fallback.into_service()) +} + +fn registry_api_v2() -> Router { + Router::new() + .route("/", get(root_handler)) + .route("/:name/blobs/:digest", head(blob_check).get(blob_check)) + .route("/:name/blobs/uploads/", post(blob_upload)) + .route( + "/:name/blobs/uploads/:uuid", + put(put_handler).patch(handle_upload), + ) + .route("/:name/manifests/:reference", put(put_manifest)) +} + +async fn fallback(request: axum::http::Request) -> impl IntoResponse { + // for debugging + println!("no route for {} {}", request.method(), request.uri()); + StatusCode::NOT_FOUND +} + +// root should return 200 OK to confirm api compliance +async fn root_handler() -> Response { + Response::builder() + .status(StatusCode::OK) + .header("Docker-Distribution-API-Version", "registry/2.0") + .body(Body::empty()) + .unwrap() +} + +#[derive(Serialize)] +pub struct RegistryErrors { + errors: Vec, +} + +#[derive(Serialize)] +pub struct RegistryError { + code: String, + message: String, + detail: serde_json::Value, +} + +async fn blob_check( + Path((_repository_name, raw_digest)): Path<(String, String)>, +) -> impl IntoResponse { + let digest = raw_digest.strip_prefix("sha256:").unwrap(); + let blob_path = PathBuf::from(REGISTRY_PATH).join(&digest); + if blob_path.exists() { + StatusCode::OK + } else { + StatusCode::NOT_FOUND + } +} + +async fn blob_upload(Path(repository_name): Path) -> impl IntoResponse { + // let value = json!({ + // "errors": [ + // { + // "code": "UNSUPPORTED", + // "message": "not implemented yet lol", + // } + // ] + // }); + + let uuid = gen_alphanumeric(16); + tokio::fs::File::create(PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid)) + .await + .unwrap(); + + Response::builder() + .status(StatusCode::ACCEPTED) + .header( + "Location", + format!("/v2/{}/blobs/uploads/{}", repository_name, uuid), + ) + .header("Docker-Upload-UUID", uuid) + .header("Range", "bytes=0-0") + .body(Body::empty()) + .unwrap() +} + +use futures::StreamExt; + +async fn handle_upload( + Path((repository_name, uuid)): Path<(String, String)>, + mut stream: BodyStream, +) -> impl IntoResponse { + // let content_length = headers.get("Content-Length").unwrap(); + // let content_range = headers.get("Content-Range").unwrap(); + // let content_type = headers.get("Content-Type").unwrap(); + // assert!(content_type == "application/octet-stream"); + let mut len = 0; + let upload_path = PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid); + let mut file = tokio::fs::OpenOptions::new() + .read(false) + .write(true) + .append(true) + .create(false) + .open(upload_path) + .await + .unwrap(); + while let Some(Ok(chunk)) = stream.next().await { + let n_bytes = file.write(&chunk).await.unwrap(); + len += n_bytes; + } + + Response::builder() + .status(StatusCode::ACCEPTED) + .header( + "Location", + format!("/v2/{}/blobs/uploads/{}", repository_name, uuid), + ) + .header("Docker-Upload-UUID", uuid) + .header("Range", format!("0-{}", len)) + .body(Body::empty()) + .unwrap() +} + +use serde::Deserialize; +#[derive(Deserialize)] +struct UploadParams { + digest: String, +} + +async fn put_handler( + Path((repository_name, uuid)): Path<(String, String)>, + Query(params): Query, + mut stream: BodyStream, +) -> impl IntoResponse { + let mut _len = 0; + let upload_path = PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid); + let mut file = tokio::fs::OpenOptions::new() + .read(false) + .write(true) + .append(true) + .create(false) + .open(&upload_path) + .await + .unwrap(); + + while let Some(Ok(chunk)) = stream.next().await { + let n_bytes = file.write(&chunk).await.unwrap(); + _len += n_bytes; + } + let digest = params.digest.strip_prefix("sha256:").unwrap(); + // TODO: check the digest + let target_path = PathBuf::from(REGISTRY_PATH).join(&digest); + tokio::fs::rename(&upload_path, &target_path).await.unwrap(); + println!("DIGEST {}", digest); + Response::builder() + .status(StatusCode::CREATED) + .header( + "Location", + format!("/v2/{}/blobs/{}", repository_name, digest), + ) + .header("Docker-Upload-UUID", uuid) + // .header("Range", format!("0-{}", len)) + .header("Docker-Content-Digest", digest) + .body(Body::empty()) + .unwrap() +} + +async fn put_manifest( + Path((repository_name, reference)): Path<(String, String)>, + mut stream: BodyStream, +) -> impl IntoResponse { + let repository_dir = PathBuf::from(REGISTRY_PATH).join(&repository_name); + + tokio::fs::create_dir_all(&repository_dir).await.unwrap(); + + let mut hasher = Sha256::new(); + { + let manifest_path = repository_dir.join(&reference).with_extension("json"); + let mut file = tokio::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .open(&manifest_path) + .await + .unwrap(); + while let Some(Ok(chunk)) = stream.next().await { + hasher.update(&chunk); + file.write(&chunk).await.unwrap(); + } + } + let digest = hasher.finalize(); + + Response::builder() + .status(StatusCode::CREATED) + .header( + "Location", + format!("/v2/{}/manifests/{}", repository_name, reference), + ) + .header("Docker-Content-Digest", format!("sha256:{:x}", digest)) + .body(Body::empty()) + .unwrap() +} -- cgit v1.2.3 From b90b3d3635f57bb84450d90544df536bf58e8588 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Fri, 17 Jun 2022 19:01:40 +0200 Subject: store blobs in sha256 directory --- planetwars-server/src/modules/registry.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index d63621a..d10532a 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -62,7 +62,7 @@ async fn blob_check( Path((_repository_name, raw_digest)): Path<(String, String)>, ) -> impl IntoResponse { let digest = raw_digest.strip_prefix("sha256:").unwrap(); - let blob_path = PathBuf::from(REGISTRY_PATH).join(&digest); + let blob_path = PathBuf::from(REGISTRY_PATH).join("sha256").join(&digest); if blob_path.exists() { StatusCode::OK } else { @@ -162,9 +162,9 @@ async fn put_handler( } let digest = params.digest.strip_prefix("sha256:").unwrap(); // TODO: check the digest - let target_path = PathBuf::from(REGISTRY_PATH).join(&digest); + let target_path = PathBuf::from(REGISTRY_PATH).join("sha256").join(&digest); tokio::fs::rename(&upload_path, &target_path).await.unwrap(); - println!("DIGEST {}", digest); + Response::builder() .status(StatusCode::CREATED) .header( @@ -182,7 +182,9 @@ async fn put_manifest( Path((repository_name, reference)): Path<(String, String)>, mut stream: BodyStream, ) -> impl IntoResponse { - let repository_dir = PathBuf::from(REGISTRY_PATH).join(&repository_name); + let repository_dir = PathBuf::from(REGISTRY_PATH) + .join("manifests") + .join(&repository_name); tokio::fs::create_dir_all(&repository_dir).await.unwrap(); -- cgit v1.2.3 From 2cde7ec673b38b51db0dce8d5e8496ba2d92aa12 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sat, 18 Jun 2022 12:42:03 +0200 Subject: support docker pull --- planetwars-server/src/modules/registry.rs | 52 ++++++++++++++++++++++++++++--- 1 file changed, 47 insertions(+), 5 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index d10532a..6095527 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -1,4 +1,4 @@ -use axum::body::Body; +use axum::body::{Body, StreamBody}; use axum::extract::{BodyStream, Path, Query}; use axum::handler::Handler; use axum::response::{IntoResponse, Response}; @@ -9,6 +9,7 @@ use serde::Serialize; use sha2::{Digest, Sha256}; use std::path::PathBuf; use tokio::io::AsyncWriteExt; +use tokio_util::io::ReaderStream; use crate::util::gen_alphanumeric; @@ -22,13 +23,16 @@ pub fn registry_service() -> Router { fn registry_api_v2() -> Router { Router::new() .route("/", get(root_handler)) - .route("/:name/blobs/:digest", head(blob_check).get(blob_check)) + .route("/:name/blobs/:digest", head(blob_check).get(get_blob)) .route("/:name/blobs/uploads/", post(blob_upload)) .route( "/:name/blobs/uploads/:uuid", put(put_handler).patch(handle_upload), ) - .route("/:name/manifests/:reference", put(put_manifest)) + .route( + "/:name/manifests/:reference", + get(get_manifest).put(put_manifest), + ) } async fn fallback(request: axum::http::Request) -> impl IntoResponse { @@ -70,6 +74,20 @@ async fn blob_check( } } +async fn get_blob( + Path((_repository_name, raw_digest)): Path<(String, String)>, +) -> impl IntoResponse { + let digest = raw_digest.strip_prefix("sha256:").unwrap(); + let blob_path = PathBuf::from(REGISTRY_PATH).join("sha256").join(&digest); + if !blob_path.exists() { + return Err(StatusCode::NOT_FOUND); + } + let file = tokio::fs::File::open(&blob_path).await.unwrap(); + let reader_stream = ReaderStream::new(file); + let stream_body = StreamBody::new(reader_stream); + Ok(stream_body) +} + async fn blob_upload(Path(repository_name): Path) -> impl IntoResponse { // let value = json!({ // "errors": [ @@ -178,6 +196,26 @@ async fn put_handler( .unwrap() } +async fn get_manifest( + Path((repository_name, reference)): Path<(String, String)>, +) -> impl IntoResponse { + let manifest_path = PathBuf::from(REGISTRY_PATH) + .join("manifests") + .join(&repository_name) + .join(&reference) + .with_extension("json"); + let data = tokio::fs::read(&manifest_path).await.unwrap(); + + let manifest: serde_json::Map = + serde_json::from_slice(&data).unwrap(); + let media_type = manifest.get("mediaType").unwrap().as_str().unwrap(); + Response::builder() + .status(StatusCode::OK) + .header("Content-Type", media_type) + .body(axum::body::Full::from(data)) + .unwrap() +} + async fn put_manifest( Path((repository_name, reference)): Path<(String, String)>, mut stream: BodyStream, @@ -189,8 +227,8 @@ async fn put_manifest( tokio::fs::create_dir_all(&repository_dir).await.unwrap(); let mut hasher = Sha256::new(); + let manifest_path = repository_dir.join(&reference).with_extension("json"); { - let manifest_path = repository_dir.join(&reference).with_extension("json"); let mut file = tokio::fs::OpenOptions::new() .write(true) .create(true) @@ -204,6 +242,10 @@ async fn put_manifest( } } let digest = hasher.finalize(); + // TODO: store content-adressable manifests separately + let content_digest = format!("sha256:{:x}", digest); + let digest_path = repository_dir.join(&content_digest).with_extension("json"); + tokio::fs::copy(manifest_path, digest_path).await.unwrap(); Response::builder() .status(StatusCode::CREATED) @@ -211,7 +253,7 @@ async fn put_manifest( "Location", format!("/v2/{}/manifests/{}", repository_name, reference), ) - .header("Docker-Content-Digest", format!("sha256:{:x}", digest)) + .header("Docker-Content-Digest", content_digest) .body(Body::empty()) .unwrap() } -- cgit v1.2.3 From 478094abcf6f79ddb4e13e5763f5827208363ae7 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sun, 19 Jun 2022 22:33:44 +0200 Subject: basic docker login PoC --- planetwars-server/src/modules/registry.rs | 57 +++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 15 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index 6095527..9d71dd7 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -1,9 +1,11 @@ -use axum::body::{Body, StreamBody}; -use axum::extract::{BodyStream, Path, Query}; +use axum::body::{Body, Bytes, StreamBody}; +use axum::extract::{BodyStream, FromRequest, Path, Query, RequestParts, TypedHeader}; use axum::handler::Handler; +use axum::headers::authorization::Basic; +use axum::headers::Authorization; use axum::response::{IntoResponse, Response}; use axum::routing::{get, head, post, put}; -use axum::Router; +use axum::{async_trait, Router}; use hyper::StatusCode; use serde::Serialize; use sha2::{Digest, Sha256}; @@ -16,7 +18,8 @@ use crate::util::gen_alphanumeric; const REGISTRY_PATH: &'static str = "./data/registry"; pub fn registry_service() -> Router { Router::new() - .nest("/v2", registry_api_v2()) + // The docker API requires this trailing slash + .nest("/v2/", registry_api_v2()) .fallback(fallback.into_service()) } @@ -41,8 +44,41 @@ async fn fallback(request: axum::http::Request) -> impl IntoResponse { StatusCode::NOT_FOUND } -// root should return 200 OK to confirm api compliance -async fn root_handler() -> Response { +type AuthorizationHeader = TypedHeader>; + +struct RegistryAuth; + +#[async_trait] +impl FromRequest for RegistryAuth +where + B: Send, +{ + type Rejection = Response>; + + async fn from_request(req: &mut RequestParts) -> Result { + let TypedHeader(Authorization(_basic)) = + AuthorizationHeader::from_request(req).await.map_err(|_| { + let err = RegistryErrors { + errors: vec![RegistryError { + code: "UNAUTHORIZED".to_string(), + message: "please log in".to_string(), + detail: serde_json::Value::Null, + }], + }; + Response::builder() + .status(StatusCode::UNAUTHORIZED) + .header("Docker-Distribution-API-Version", "registry/2.0") + .header("WWW-Authenticate", "Basic") + .body(axum::body::Full::from(serde_json::to_vec(&err).unwrap())) + .unwrap() + })?; + + Ok(RegistryAuth) + } +} + +async fn root_handler(_auth: RegistryAuth) -> impl IntoResponse { + // root should return 200 OK to confirm api compliance Response::builder() .status(StatusCode::OK) .header("Docker-Distribution-API-Version", "registry/2.0") @@ -89,15 +125,6 @@ async fn get_blob( } async fn blob_upload(Path(repository_name): Path) -> impl IntoResponse { - // let value = json!({ - // "errors": [ - // { - // "code": "UNSUPPORTED", - // "message": "not implemented yet lol", - // } - // ] - // }); - let uuid = gen_alphanumeric(16); tokio::fs::File::create(PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid)) .await -- cgit v1.2.3 From a2a8a41689ad07eb2236ee438e9d01266946008d Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Mon, 20 Jun 2022 20:27:51 +0200 Subject: rename route handler methods --- planetwars-server/src/modules/registry.rs | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index 9d71dd7..61652d9 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -25,17 +25,20 @@ pub fn registry_service() -> Router { fn registry_api_v2() -> Router { Router::new() - .route("/", get(root_handler)) - .route("/:name/blobs/:digest", head(blob_check).get(get_blob)) - .route("/:name/blobs/uploads/", post(blob_upload)) - .route( - "/:name/blobs/uploads/:uuid", - put(put_handler).patch(handle_upload), - ) + .route("/", get(get_root)) .route( "/:name/manifests/:reference", get(get_manifest).put(put_manifest), ) + .route( + "/:name/blobs/:digest", + head(check_blob_exists).get(get_blob), + ) + .route("/:name/blobs/uploads/", post(create_upload)) + .route( + "/:name/blobs/uploads/:uuid", + put(put_upload).patch(patch_upload), + ) } async fn fallback(request: axum::http::Request) -> impl IntoResponse { @@ -77,7 +80,7 @@ where } } -async fn root_handler(_auth: RegistryAuth) -> impl IntoResponse { +async fn get_root(_auth: RegistryAuth) -> impl IntoResponse { // root should return 200 OK to confirm api compliance Response::builder() .status(StatusCode::OK) @@ -98,7 +101,7 @@ pub struct RegistryError { detail: serde_json::Value, } -async fn blob_check( +async fn check_blob_exists( Path((_repository_name, raw_digest)): Path<(String, String)>, ) -> impl IntoResponse { let digest = raw_digest.strip_prefix("sha256:").unwrap(); @@ -124,7 +127,7 @@ async fn get_blob( Ok(stream_body) } -async fn blob_upload(Path(repository_name): Path) -> impl IntoResponse { +async fn create_upload(Path(repository_name): Path) -> impl IntoResponse { let uuid = gen_alphanumeric(16); tokio::fs::File::create(PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid)) .await @@ -144,7 +147,7 @@ async fn blob_upload(Path(repository_name): Path) -> impl IntoResponse { use futures::StreamExt; -async fn handle_upload( +async fn patch_upload( Path((repository_name, uuid)): Path<(String, String)>, mut stream: BodyStream, ) -> impl IntoResponse { @@ -185,7 +188,7 @@ struct UploadParams { digest: String, } -async fn put_handler( +async fn put_upload( Path((repository_name, uuid)): Path<(String, String)>, Query(params): Query, mut stream: BodyStream, -- cgit v1.2.3 From 059cd4fa0e1da6e3d9b2edaae62d2e58e2f37924 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Mon, 20 Jun 2022 22:14:15 +0200 Subject: implement basic auth checking --- planetwars-server/src/modules/registry.rs | 86 ++++++++++++++++++++++--------- 1 file changed, 63 insertions(+), 23 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index 61652d9..a866dce 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -1,4 +1,4 @@ -use axum::body::{Body, Bytes, StreamBody}; +use axum::body::{Body, StreamBody}; use axum::extract::{BodyStream, FromRequest, Path, Query, RequestParts, TypedHeader}; use axum::handler::Handler; use axum::headers::authorization::Basic; @@ -14,8 +14,12 @@ use tokio::io::AsyncWriteExt; use tokio_util::io::ReaderStream; use crate::util::gen_alphanumeric; +use crate::DatabaseConnection; + +use crate::db::users::{authenticate_user, Credentials, User}; + +const REGISTRY_PATH: &str = "./data/registry"; -const REGISTRY_PATH: &'static str = "./data/registry"; pub fn registry_service() -> Router { Router::new() // The docker API requires this trailing slash @@ -49,34 +53,61 @@ async fn fallback(request: axum::http::Request) -> impl IntoResponse { type AuthorizationHeader = TypedHeader>; -struct RegistryAuth; +enum RegistryAuth { + User(User), +} + +enum RegistryAuthError { + NoAuthHeader, + InvalidCredentials, +} + +impl IntoResponse for RegistryAuthError { + fn into_response(self) -> Response { + // TODO: create enum for registry errors + let err = RegistryErrors { + errors: vec![RegistryError { + code: "UNAUTHORIZED".to_string(), + message: "please log in".to_string(), + detail: serde_json::Value::Null, + }], + }; + + ( + StatusCode::UNAUTHORIZED, + [ + ("Docker-Distribution-API-Version", "registry/2.0"), + ("WWW-Authenticate", "Basic"), + ], + serde_json::to_string(&err).unwrap(), + ) + .into_response() + } +} #[async_trait] impl FromRequest for RegistryAuth where B: Send, { - type Rejection = Response>; + type Rejection = RegistryAuthError; async fn from_request(req: &mut RequestParts) -> Result { - let TypedHeader(Authorization(_basic)) = - AuthorizationHeader::from_request(req).await.map_err(|_| { - let err = RegistryErrors { - errors: vec![RegistryError { - code: "UNAUTHORIZED".to_string(), - message: "please log in".to_string(), - detail: serde_json::Value::Null, - }], - }; - Response::builder() - .status(StatusCode::UNAUTHORIZED) - .header("Docker-Distribution-API-Version", "registry/2.0") - .header("WWW-Authenticate", "Basic") - .body(axum::body::Full::from(serde_json::to_vec(&err).unwrap())) - .unwrap() - })?; - - Ok(RegistryAuth) + let db_conn = DatabaseConnection::from_request(req).await.unwrap(); + + let TypedHeader(Authorization(basic)) = AuthorizationHeader::from_request(req) + .await + .map_err(|_| RegistryAuthError::NoAuthHeader)?; + + // TODO: Into would be nice + let credentials = Credentials { + username: basic.username(), + password: basic.password(), + }; + let user = authenticate_user(&credentials, &db_conn) + .ok_or(RegistryAuthError::InvalidCredentials)?; + + Ok(RegistryAuth::User(user)) } } @@ -102,6 +133,7 @@ pub struct RegistryError { } async fn check_blob_exists( + _auth: RegistryAuth, Path((_repository_name, raw_digest)): Path<(String, String)>, ) -> impl IntoResponse { let digest = raw_digest.strip_prefix("sha256:").unwrap(); @@ -114,6 +146,7 @@ async fn check_blob_exists( } async fn get_blob( + _auth: RegistryAuth, Path((_repository_name, raw_digest)): Path<(String, String)>, ) -> impl IntoResponse { let digest = raw_digest.strip_prefix("sha256:").unwrap(); @@ -127,7 +160,10 @@ async fn get_blob( Ok(stream_body) } -async fn create_upload(Path(repository_name): Path) -> impl IntoResponse { +async fn create_upload( + _auth: RegistryAuth, + Path(repository_name): Path, +) -> impl IntoResponse { let uuid = gen_alphanumeric(16); tokio::fs::File::create(PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid)) .await @@ -148,6 +184,7 @@ async fn create_upload(Path(repository_name): Path) -> impl IntoResponse use futures::StreamExt; async fn patch_upload( + _auth: RegistryAuth, Path((repository_name, uuid)): Path<(String, String)>, mut stream: BodyStream, ) -> impl IntoResponse { @@ -189,6 +226,7 @@ struct UploadParams { } async fn put_upload( + _auth: RegistryAuth, Path((repository_name, uuid)): Path<(String, String)>, Query(params): Query, mut stream: BodyStream, @@ -227,6 +265,7 @@ async fn put_upload( } async fn get_manifest( + _auth: RegistryAuth, Path((repository_name, reference)): Path<(String, String)>, ) -> impl IntoResponse { let manifest_path = PathBuf::from(REGISTRY_PATH) @@ -247,6 +286,7 @@ async fn get_manifest( } async fn put_manifest( + _auth: RegistryAuth, Path((repository_name, reference)): Path<(String, String)>, mut stream: BodyStream, ) -> impl IntoResponse { -- cgit v1.2.3 From 381ce040fda929f65c681d4134a03e3143659243 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Tue, 21 Jun 2022 22:45:59 +0200 Subject: add auth to all registry routes --- planetwars-server/src/modules/registry.rs | 106 +++++++++++++++++++++--------- 1 file changed, 75 insertions(+), 31 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index a866dce..8bc3a7d 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -6,6 +6,7 @@ use axum::headers::Authorization; use axum::response::{IntoResponse, Response}; use axum::routing::{get, head, post, put}; use axum::{async_trait, Router}; +use futures::StreamExt; use hyper::StatusCode; use serde::Serialize; use sha2::{Digest, Sha256}; @@ -14,7 +15,7 @@ use tokio::io::AsyncWriteExt; use tokio_util::io::ReaderStream; use crate::util::gen_alphanumeric; -use crate::DatabaseConnection; +use crate::{db, DatabaseConnection}; use crate::db::users::{authenticate_user, Credentials, User}; @@ -133,22 +134,28 @@ pub struct RegistryError { } async fn check_blob_exists( - _auth: RegistryAuth, - Path((_repository_name, raw_digest)): Path<(String, String)>, -) -> impl IntoResponse { + db_conn: DatabaseConnection, + auth: RegistryAuth, + Path((repository_name, raw_digest)): Path<(String, String)>, +) -> Result { + check_access(&repository_name, &auth, &db_conn)?; + let digest = raw_digest.strip_prefix("sha256:").unwrap(); let blob_path = PathBuf::from(REGISTRY_PATH).join("sha256").join(&digest); if blob_path.exists() { - StatusCode::OK + Ok(StatusCode::OK) } else { - StatusCode::NOT_FOUND + Err(StatusCode::NOT_FOUND) } } async fn get_blob( - _auth: RegistryAuth, - Path((_repository_name, raw_digest)): Path<(String, String)>, -) -> impl IntoResponse { + db_conn: DatabaseConnection, + auth: RegistryAuth, + Path((repository_name, raw_digest)): Path<(String, String)>, +) -> Result { + check_access(&repository_name, &auth, &db_conn)?; + let digest = raw_digest.strip_prefix("sha256:").unwrap(); let blob_path = PathBuf::from(REGISTRY_PATH).join("sha256").join(&digest); if !blob_path.exists() { @@ -161,15 +168,18 @@ async fn get_blob( } async fn create_upload( - _auth: RegistryAuth, + db_conn: DatabaseConnection, + auth: RegistryAuth, Path(repository_name): Path, -) -> impl IntoResponse { +) -> Result { + check_access(&repository_name, &auth, &db_conn)?; + let uuid = gen_alphanumeric(16); tokio::fs::File::create(PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid)) .await .unwrap(); - Response::builder() + Ok(Response::builder() .status(StatusCode::ACCEPTED) .header( "Location", @@ -178,16 +188,17 @@ async fn create_upload( .header("Docker-Upload-UUID", uuid) .header("Range", "bytes=0-0") .body(Body::empty()) - .unwrap() + .unwrap()) } -use futures::StreamExt; - async fn patch_upload( - _auth: RegistryAuth, + db_conn: DatabaseConnection, + auth: RegistryAuth, Path((repository_name, uuid)): Path<(String, String)>, mut stream: BodyStream, -) -> impl IntoResponse { +) -> Result { + check_access(&repository_name, &auth, &db_conn)?; + // let content_length = headers.get("Content-Length").unwrap(); // let content_range = headers.get("Content-Range").unwrap(); // let content_type = headers.get("Content-Type").unwrap(); @@ -207,7 +218,7 @@ async fn patch_upload( len += n_bytes; } - Response::builder() + Ok(Response::builder() .status(StatusCode::ACCEPTED) .header( "Location", @@ -216,7 +227,7 @@ async fn patch_upload( .header("Docker-Upload-UUID", uuid) .header("Range", format!("0-{}", len)) .body(Body::empty()) - .unwrap() + .unwrap()) } use serde::Deserialize; @@ -226,11 +237,14 @@ struct UploadParams { } async fn put_upload( - _auth: RegistryAuth, + db_conn: DatabaseConnection, + auth: RegistryAuth, Path((repository_name, uuid)): Path<(String, String)>, Query(params): Query, mut stream: BodyStream, -) -> impl IntoResponse { +) -> Result { + check_access(&repository_name, &auth, &db_conn)?; + let mut _len = 0; let upload_path = PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid); let mut file = tokio::fs::OpenOptions::new() @@ -251,7 +265,7 @@ async fn put_upload( let target_path = PathBuf::from(REGISTRY_PATH).join("sha256").join(&digest); tokio::fs::rename(&upload_path, &target_path).await.unwrap(); - Response::builder() + Ok(Response::builder() .status(StatusCode::CREATED) .header( "Location", @@ -261,13 +275,16 @@ async fn put_upload( // .header("Range", format!("0-{}", len)) .header("Docker-Content-Digest", digest) .body(Body::empty()) - .unwrap() + .unwrap()) } async fn get_manifest( - _auth: RegistryAuth, + db_conn: DatabaseConnection, + auth: RegistryAuth, Path((repository_name, reference)): Path<(String, String)>, -) -> impl IntoResponse { +) -> Result { + check_access(&repository_name, &auth, &db_conn)?; + let manifest_path = PathBuf::from(REGISTRY_PATH) .join("manifests") .join(&repository_name) @@ -278,18 +295,21 @@ async fn get_manifest( let manifest: serde_json::Map = serde_json::from_slice(&data).unwrap(); let media_type = manifest.get("mediaType").unwrap().as_str().unwrap(); - Response::builder() + Ok(Response::builder() .status(StatusCode::OK) .header("Content-Type", media_type) .body(axum::body::Full::from(data)) - .unwrap() + .unwrap()) } async fn put_manifest( - _auth: RegistryAuth, + db_conn: DatabaseConnection, + auth: RegistryAuth, Path((repository_name, reference)): Path<(String, String)>, mut stream: BodyStream, -) -> impl IntoResponse { +) -> Result { + check_access(&repository_name, &auth, &db_conn)?; + let repository_dir = PathBuf::from(REGISTRY_PATH) .join("manifests") .join(&repository_name); @@ -317,7 +337,7 @@ async fn put_manifest( let digest_path = repository_dir.join(&content_digest).with_extension("json"); tokio::fs::copy(manifest_path, digest_path).await.unwrap(); - Response::builder() + Ok(Response::builder() .status(StatusCode::CREATED) .header( "Location", @@ -325,5 +345,29 @@ async fn put_manifest( ) .header("Docker-Content-Digest", content_digest) .body(Body::empty()) - .unwrap() + .unwrap()) +} + +fn check_access( + repository_name: &str, + auth: &RegistryAuth, + db_conn: &DatabaseConnection, +) -> Result<(), StatusCode> { + use diesel::OptionalExtension; + + let res = db::bots::find_bot_by_name(repository_name, db_conn) + .optional() + .expect("could not run query"); + + match res { + None => Ok(()), // name has not been claimed yet (TODO: verify its validity) + Some(existing_bot) => { + let RegistryAuth::User(user) = auth; + if existing_bot.owner_id == Some(user.id) { + Ok(()) + } else { + Err(StatusCode::FORBIDDEN) + } + } + } } -- cgit v1.2.3 From f6fca3818a5f5e32afd02280c04fdbe77972075f Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Fri, 24 Jun 2022 19:32:22 +0200 Subject: don't allow accessing non-existing repositories --- planetwars-server/src/modules/registry.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index 8bc3a7d..c0e12d0 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -360,7 +360,7 @@ fn check_access( .expect("could not run query"); match res { - None => Ok(()), // name has not been claimed yet (TODO: verify its validity) + None => Err(StatusCode::FORBIDDEN), Some(existing_bot) => { let RegistryAuth::User(user) = auth; if existing_bot.owner_id == Some(user.id) { -- cgit v1.2.3 From d7e4a1fd5cb1ab7438d281de6dfe26013623dc6b Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Mon, 27 Jun 2022 21:20:05 +0200 Subject: implement admin login --- planetwars-server/src/modules/registry.rs | 41 ++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 12 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index c0e12d0..346f5d9 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -52,10 +52,15 @@ async fn fallback(request: axum::http::Request) -> impl IntoResponse { StatusCode::NOT_FOUND } +const ADMIN_USERNAME: &str = "admin"; +// TODO: put this in some configuration +const ADMIN_PASSWORD: &str = "supersecretpassword"; + type AuthorizationHeader = TypedHeader>; enum RegistryAuth { User(User), + Admin, } enum RegistryAuthError { @@ -94,8 +99,6 @@ where type Rejection = RegistryAuthError; async fn from_request(req: &mut RequestParts) -> Result { - let db_conn = DatabaseConnection::from_request(req).await.unwrap(); - let TypedHeader(Authorization(basic)) = AuthorizationHeader::from_request(req) .await .map_err(|_| RegistryAuthError::NoAuthHeader)?; @@ -105,10 +108,20 @@ where username: basic.username(), password: basic.password(), }; - let user = authenticate_user(&credentials, &db_conn) - .ok_or(RegistryAuthError::InvalidCredentials)?; - Ok(RegistryAuth::User(user)) + if credentials.username == ADMIN_USERNAME { + if credentials.password == ADMIN_PASSWORD { + Ok(RegistryAuth::Admin) + } else { + Err(RegistryAuthError::InvalidCredentials) + } + } else { + let db_conn = DatabaseConnection::from_request(req).await.unwrap(); + let user = authenticate_user(&credentials, &db_conn) + .ok_or(RegistryAuthError::InvalidCredentials)?; + + Ok(RegistryAuth::User(user)) + } } } @@ -348,6 +361,8 @@ async fn put_manifest( .unwrap()) } +/// Ensure that the accessed repository exists +/// and the user is allowed to access ti fn check_access( repository_name: &str, auth: &RegistryAuth, @@ -355,15 +370,17 @@ fn check_access( ) -> Result<(), StatusCode> { use diesel::OptionalExtension; - let res = db::bots::find_bot_by_name(repository_name, db_conn) + // TODO: it would be nice to provide the found repository + // to the route handlers + let bot = db::bots::find_bot_by_name(repository_name, db_conn) .optional() - .expect("could not run query"); + .expect("could not run query") + .ok_or(StatusCode::NOT_FOUND)?; - match res { - None => Err(StatusCode::FORBIDDEN), - Some(existing_bot) => { - let RegistryAuth::User(user) = auth; - if existing_bot.owner_id == Some(user.id) { + match &auth { + RegistryAuth::Admin => Ok(()), + RegistryAuth::User(user) => { + if bot.owner_id == Some(user.id) { Ok(()) } else { Err(StatusCode::FORBIDDEN) -- cgit v1.2.3 From 4d1c0a3289a295ea27eea51ec0a91c4229a92edc Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Thu, 30 Jun 2022 20:28:37 +0200 Subject: make sure that all pushed data is actually written --- planetwars-server/src/modules/registry.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index 346f5d9..7adb764 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -227,8 +227,8 @@ async fn patch_upload( .await .unwrap(); while let Some(Ok(chunk)) = stream.next().await { - let n_bytes = file.write(&chunk).await.unwrap(); - len += n_bytes; + file.write_all(&chunk).await.unwrap(); + len += chunk.len(); } Ok(Response::builder() @@ -270,9 +270,10 @@ async fn put_upload( .unwrap(); while let Some(Ok(chunk)) = stream.next().await { - let n_bytes = file.write(&chunk).await.unwrap(); - _len += n_bytes; + file.write_all(&chunk).await.unwrap(); + _len += chunk.len(); } + let digest = params.digest.strip_prefix("sha256:").unwrap(); // TODO: check the digest let target_path = PathBuf::from(REGISTRY_PATH).join("sha256").join(&digest); -- cgit v1.2.3 From 419029738dd914bd0c8edd9c8d4365cac2d53ad7 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Thu, 30 Jun 2022 20:49:10 +0200 Subject: verify blob digest on upload --- planetwars-server/src/modules/registry.rs | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index 7adb764..6e29878 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -125,6 +125,15 @@ where } } +// Since async file io just calls spawn_blocking internally, it does not really make sense +// to make this an async function +fn file_sha256_digest(path: &std::path::Path) -> std::io::Result { + let mut file = std::fs::File::open(path)?; + let mut hasher = Sha256::new(); + let _n = std::io::copy(&mut file, &mut hasher)?; + Ok(format!("{:x}", hasher.finalize())) +} + async fn get_root(_auth: RegistryAuth) -> impl IntoResponse { // root should return 200 OK to confirm api compliance Response::builder() @@ -273,9 +282,15 @@ async fn put_upload( file.write_all(&chunk).await.unwrap(); _len += chunk.len(); } + file.flush().await.unwrap(); + + let expected_digest = params.digest.strip_prefix("sha256:").unwrap(); + let digest = file_sha256_digest(&upload_path).unwrap(); + if digest != expected_digest { + // TODO: return a docker error body + return Err(StatusCode::BAD_REQUEST); + } - let digest = params.digest.strip_prefix("sha256:").unwrap(); - // TODO: check the digest let target_path = PathBuf::from(REGISTRY_PATH).join("sha256").join(&digest); tokio::fs::rename(&upload_path, &target_path).await.unwrap(); @@ -286,8 +301,9 @@ async fn put_upload( format!("/v2/{}/blobs/{}", repository_name, digest), ) .header("Docker-Upload-UUID", uuid) - // .header("Range", format!("0-{}", len)) - .header("Docker-Content-Digest", digest) + // TODO: set content-range + // .header("Content-Range", format!("0-{}", len)) + .header("Docker-Content-Digest", params.digest) .body(Body::empty()) .unwrap()) } @@ -342,7 +358,7 @@ async fn put_manifest( .unwrap(); while let Some(Ok(chunk)) = stream.next().await { hasher.update(&chunk); - file.write(&chunk).await.unwrap(); + file.write_all(&chunk).await.unwrap(); } } let digest = hasher.finalize(); -- cgit v1.2.3 From 7b88bb0502f67e913b6e8bca394428fd2df45cc2 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Fri, 1 Jul 2022 20:45:26 +0200 Subject: use file metadata for returning data ranges and lengths --- planetwars-server/src/modules/registry.rs | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index 6e29878..d73e7e9 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -134,6 +134,13 @@ fn file_sha256_digest(path: &std::path::Path) -> std::io::Result { Ok(format!("{:x}", hasher.finalize())) } +/// Get the index of the last byte in a file +async fn last_byte_pos(file: &tokio::fs::File) -> std::io::Result { + let n_bytes = file.metadata().await?.len(); + let pos = if n_bytes == 0 { 0 } else { n_bytes - 1 }; + Ok(pos) +} + async fn get_root(_auth: RegistryAuth) -> impl IntoResponse { // root should return 200 OK to confirm api compliance Response::builder() @@ -165,7 +172,8 @@ async fn check_blob_exists( let digest = raw_digest.strip_prefix("sha256:").unwrap(); let blob_path = PathBuf::from(REGISTRY_PATH).join("sha256").join(&digest); if blob_path.exists() { - Ok(StatusCode::OK) + let metadata = std::fs::metadata(&blob_path).unwrap(); + Ok((StatusCode::OK, [("Content-Length", metadata.len())])) } else { Err(StatusCode::NOT_FOUND) } @@ -221,11 +229,7 @@ async fn patch_upload( ) -> Result { check_access(&repository_name, &auth, &db_conn)?; - // let content_length = headers.get("Content-Length").unwrap(); - // let content_range = headers.get("Content-Range").unwrap(); - // let content_type = headers.get("Content-Type").unwrap(); - // assert!(content_type == "application/octet-stream"); - let mut len = 0; + // TODO: support content range header in request let upload_path = PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid); let mut file = tokio::fs::OpenOptions::new() .read(false) @@ -237,9 +241,10 @@ async fn patch_upload( .unwrap(); while let Some(Ok(chunk)) = stream.next().await { file.write_all(&chunk).await.unwrap(); - len += chunk.len(); } + let last_byte = last_byte_pos(&file).await.unwrap(); + Ok(Response::builder() .status(StatusCode::ACCEPTED) .header( @@ -247,7 +252,8 @@ async fn patch_upload( format!("/v2/{}/blobs/uploads/{}", repository_name, uuid), ) .header("Docker-Upload-UUID", uuid) - .header("Range", format!("0-{}", len)) + // range indicating current progress of the upload + .header("Range", format!("0-{}", last_byte)) .body(Body::empty()) .unwrap()) } @@ -267,7 +273,6 @@ async fn put_upload( ) -> Result { check_access(&repository_name, &auth, &db_conn)?; - let mut _len = 0; let upload_path = PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid); let mut file = tokio::fs::OpenOptions::new() .read(false) @@ -278,11 +283,12 @@ async fn put_upload( .await .unwrap(); + let range_begin = last_byte_pos(&file).await.unwrap(); while let Some(Ok(chunk)) = stream.next().await { file.write_all(&chunk).await.unwrap(); - _len += chunk.len(); } file.flush().await.unwrap(); + let range_end = last_byte_pos(&file).await.unwrap(); let expected_digest = params.digest.strip_prefix("sha256:").unwrap(); let digest = file_sha256_digest(&upload_path).unwrap(); @@ -301,8 +307,8 @@ async fn put_upload( format!("/v2/{}/blobs/{}", repository_name, digest), ) .header("Docker-Upload-UUID", uuid) - // TODO: set content-range - // .header("Content-Range", format!("0-{}", len)) + // content range for bytes that were in the body of this request + .header("Content-Range", format!("{}-{}", range_begin, range_end)) .header("Docker-Content-Digest", params.digest) .body(Body::empty()) .unwrap()) -- cgit v1.2.3 From bbed87755419f97b0ee8967617af0c6573c168af Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Mon, 4 Jul 2022 20:11:29 +0200 Subject: cleanup and comments --- planetwars-server/src/modules/registry.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index d73e7e9..c8ec4fa 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -1,6 +1,7 @@ +// TODO: this module is functional, but it needs a good refactor for proper error handling. + use axum::body::{Body, StreamBody}; use axum::extract::{BodyStream, FromRequest, Path, Query, RequestParts, TypedHeader}; -use axum::handler::Handler; use axum::headers::authorization::Basic; use axum::headers::Authorization; use axum::response::{IntoResponse, Response}; @@ -19,13 +20,13 @@ use crate::{db, DatabaseConnection}; use crate::db::users::{authenticate_user, Credentials, User}; +// TODO: put this in a config file const REGISTRY_PATH: &str = "./data/registry"; pub fn registry_service() -> Router { Router::new() // The docker API requires this trailing slash .nest("/v2/", registry_api_v2()) - .fallback(fallback.into_service()) } fn registry_api_v2() -> Router { @@ -46,12 +47,6 @@ fn registry_api_v2() -> Router { ) } -async fn fallback(request: axum::http::Request) -> impl IntoResponse { - // for debugging - println!("no route for {} {}", request.method(), request.uri()); - StatusCode::NOT_FOUND -} - const ADMIN_USERNAME: &str = "admin"; // TODO: put this in some configuration const ADMIN_PASSWORD: &str = "supersecretpassword"; -- cgit v1.2.3 From b3df5c6f8cc59e099a2f1db3df8089af4abca02e Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Tue, 5 Jul 2022 20:34:20 +0200 Subject: migrate code_bundles to bot_versions --- planetwars-server/src/modules/bots.rs | 2 +- planetwars-server/src/modules/matches.rs | 5 +++-- planetwars-server/src/modules/ranking.rs | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bots.rs b/planetwars-server/src/modules/bots.rs index 843e48d..ddc1589 100644 --- a/planetwars-server/src/modules/bots.rs +++ b/planetwars-server/src/modules/bots.rs @@ -17,7 +17,7 @@ pub fn save_code_bundle( let new_code_bundle = db::bots::NewCodeBundle { bot_id, - path: &bundle_name, + code_bundle_path: &bundle_name, }; db::bots::create_code_bundle(&new_code_bundle, conn) } diff --git a/planetwars-server/src/modules/matches.rs b/planetwars-server/src/modules/matches.rs index 6d9261d..7d6a1dc 100644 --- a/planetwars-server/src/modules/matches.rs +++ b/planetwars-server/src/modules/matches.rs @@ -98,7 +98,8 @@ impl RunMatch { } pub fn code_bundle_to_botspec(code_bundle: &db::bots::CodeBundle) -> Box { - let bundle_path = PathBuf::from(BOTS_DIR).join(&code_bundle.path); + // TODO: get rid of this unwrap + let bundle_path = PathBuf::from(BOTS_DIR).join(code_bundle.code_bundle_path.as_ref().unwrap()); Box::new(DockerBotSpec { code_path: bundle_path, @@ -126,5 +127,5 @@ async fn run_match_task( db::matches::save_match_result(match_id, result, &conn).expect("could not save match result"); - return outcome; + outcome } diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs index 72156ee..b1ad0da 100644 --- a/planetwars-server/src/modules/ranking.rs +++ b/planetwars-server/src/modules/ranking.rs @@ -1,8 +1,8 @@ use crate::{db::bots::Bot, DbPool}; use crate::db; -use diesel::{PgConnection, QueryResult}; use crate::modules::matches::{MatchPlayer, RunMatch}; +use diesel::{PgConnection, QueryResult}; use rand::seq::SliceRandom; use std::collections::HashMap; use std::mem; -- cgit v1.2.3 From d7b7585dd70f9d41184cf88c2ecbd88341898c38 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Wed, 6 Jul 2022 22:41:27 +0200 Subject: rename code_bundle to bot_version --- planetwars-server/src/modules/bot_api.rs | 2 +- planetwars-server/src/modules/bots.rs | 2 +- planetwars-server/src/modules/matches.rs | 4 ++-- planetwars-server/src/modules/ranking.rs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index 0ecbf71..6324010 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -104,7 +104,7 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { let opponent = db::bots::find_bot_by_name(&match_request.opponent_name, &conn) .map_err(|_| Status::not_found("opponent not found"))?; - let opponent_code_bundle = db::bots::active_code_bundle(opponent.id, &conn) + let opponent_code_bundle = db::bots::active_bot_version(opponent.id, &conn) .map_err(|_| Status::not_found("opponent has no code"))?; let player_key = gen_alphanumeric(32); diff --git a/planetwars-server/src/modules/bots.rs b/planetwars-server/src/modules/bots.rs index ddc1589..cd26ee0 100644 --- a/planetwars-server/src/modules/bots.rs +++ b/planetwars-server/src/modules/bots.rs @@ -8,7 +8,7 @@ pub fn save_code_bundle( bot_code: &str, bot_id: Option, conn: &PgConnection, -) -> QueryResult { +) -> QueryResult { let bundle_name = gen_alphanumeric(16); let code_bundle_dir = PathBuf::from(BOTS_DIR).join(&bundle_name); diff --git a/planetwars-server/src/modules/matches.rs b/planetwars-server/src/modules/matches.rs index 7d6a1dc..4a5a980 100644 --- a/planetwars-server/src/modules/matches.rs +++ b/planetwars-server/src/modules/matches.rs @@ -29,7 +29,7 @@ pub struct MatchPlayer { } impl MatchPlayer { - pub fn from_code_bundle(code_bundle: &db::bots::CodeBundle) -> Self { + pub fn from_code_bundle(code_bundle: &db::bots::BotVersion) -> Self { MatchPlayer { bot_spec: code_bundle_to_botspec(code_bundle), code_bundle_id: Some(code_bundle.id), @@ -97,7 +97,7 @@ impl RunMatch { } } -pub fn code_bundle_to_botspec(code_bundle: &db::bots::CodeBundle) -> Box { +pub fn code_bundle_to_botspec(code_bundle: &db::bots::BotVersion) -> Box { // TODO: get rid of this unwrap let bundle_path = PathBuf::from(BOTS_DIR).join(code_bundle.code_bundle_path.as_ref().unwrap()); diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs index b1ad0da..751c35e 100644 --- a/planetwars-server/src/modules/ranking.rs +++ b/planetwars-server/src/modules/ranking.rs @@ -39,7 +39,7 @@ async fn play_ranking_match(selected_bots: Vec, db_pool: DbPool) { let db_conn = db_pool.get().await.expect("could not get db pool"); let mut code_bundles = Vec::new(); for bot in &selected_bots { - let code_bundle = db::bots::active_code_bundle(bot.id, &db_conn) + let code_bundle = db::bots::active_bot_version(bot.id, &db_conn) .expect("could not get active code bundle"); code_bundles.push(code_bundle); } -- cgit v1.2.3 From 6ec792e3bd633a0b3971e401d29b2f8671f38b14 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Thu, 7 Jul 2022 18:57:46 +0200 Subject: NewBotVersion --- planetwars-server/src/modules/bots.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bots.rs b/planetwars-server/src/modules/bots.rs index cd26ee0..629ecf6 100644 --- a/planetwars-server/src/modules/bots.rs +++ b/planetwars-server/src/modules/bots.rs @@ -15,9 +15,10 @@ pub fn save_code_bundle( std::fs::create_dir(&code_bundle_dir).unwrap(); std::fs::write(code_bundle_dir.join("bot.py"), bot_code).unwrap(); - let new_code_bundle = db::bots::NewCodeBundle { + let new_code_bundle = db::bots::NewBotVersion { bot_id, - code_bundle_path: &bundle_name, + code_bundle_path: Some(&bundle_name), + container_digest: None, }; - db::bots::create_code_bundle(&new_code_bundle, conn) + db::bots::create_bot_version(&new_code_bundle, conn) } -- cgit v1.2.3 From 0f14dee499f48b11fc329164c30cd475400a9f4d Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Thu, 7 Jul 2022 19:13:55 +0200 Subject: refactor: rename save_code_bundle to save_code_string --- planetwars-server/src/modules/bots.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bots.rs b/planetwars-server/src/modules/bots.rs index 629ecf6..b82ad41 100644 --- a/planetwars-server/src/modules/bots.rs +++ b/planetwars-server/src/modules/bots.rs @@ -4,7 +4,8 @@ use diesel::{PgConnection, QueryResult}; use crate::{db, util::gen_alphanumeric, BOTS_DIR}; -pub fn save_code_bundle( +/// Save a string containing bot code as a code bundle. +pub fn save_code_string( bot_code: &str, bot_id: Option, conn: &PgConnection, -- cgit v1.2.3 From 7eb02a2efc8f0bb8ec411c5af0f648aeda939226 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Fri, 8 Jul 2022 20:40:20 +0200 Subject: create a new bot verison on docker push --- planetwars-server/src/modules/registry.rs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index c8ec4fa..7198a61 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -15,6 +15,7 @@ use std::path::PathBuf; use tokio::io::AsyncWriteExt; use tokio_util::io::ReaderStream; +use crate::db::bots::NewBotVersion; use crate::util::gen_alphanumeric; use crate::{db, DatabaseConnection}; @@ -339,7 +340,7 @@ async fn put_manifest( Path((repository_name, reference)): Path<(String, String)>, mut stream: BodyStream, ) -> Result { - check_access(&repository_name, &auth, &db_conn)?; + let bot = check_access(&repository_name, &auth, &db_conn)?; let repository_dir = PathBuf::from(REGISTRY_PATH) .join("manifests") @@ -368,6 +369,15 @@ async fn put_manifest( let digest_path = repository_dir.join(&content_digest).with_extension("json"); tokio::fs::copy(manifest_path, digest_path).await.unwrap(); + // Register the new image as a bot version + // TODO: how should tags be handled? + let new_version = NewBotVersion { + bot_id: Some(bot.id), + code_bundle_path: None, + container_digest: Some(&content_digest), + }; + db::bots::create_bot_version(&new_version, &db_conn).expect("could not save bot version"); + Ok(Response::builder() .status(StatusCode::CREATED) .header( @@ -380,12 +390,13 @@ async fn put_manifest( } /// Ensure that the accessed repository exists -/// and the user is allowed to access ti +/// and the user is allowed to access it. +/// Returns the associated bot. fn check_access( repository_name: &str, auth: &RegistryAuth, db_conn: &DatabaseConnection, -) -> Result<(), StatusCode> { +) -> Result { use diesel::OptionalExtension; // TODO: it would be nice to provide the found repository @@ -396,10 +407,10 @@ fn check_access( .ok_or(StatusCode::NOT_FOUND)?; match &auth { - RegistryAuth::Admin => Ok(()), + RegistryAuth::Admin => Ok(bot), RegistryAuth::User(user) => { if bot.owner_id == Some(user.id) { - Ok(()) + Ok(bot) } else { Err(StatusCode::FORBIDDEN) } -- cgit v1.2.3 From ec1d50f655c05d9dec0c4b01fd1039e9c5525f34 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sat, 9 Jul 2022 20:01:05 +0200 Subject: refactor: pass on both Bot and BotVersion to MatchPlayer --- planetwars-server/src/modules/bot_api.rs | 2 +- planetwars-server/src/modules/matches.rs | 41 +++++++++++++++++++++++++------- planetwars-server/src/modules/ranking.rs | 14 ++++------- 3 files changed, 39 insertions(+), 18 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index 6324010..732aa21 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -115,7 +115,7 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { }); let mut run_match = RunMatch::from_players(vec![ MatchPlayer::from_bot_spec(remote_bot_spec), - MatchPlayer::from_code_bundle(&opponent_code_bundle), + MatchPlayer::from_bot_version(&opponent, &opponent_code_bundle), ]); let created_match = run_match .store_in_database(&conn) diff --git a/planetwars-server/src/modules/matches.rs b/planetwars-server/src/modules/matches.rs index 4a5a980..a8c7ca9 100644 --- a/planetwars-server/src/modules/matches.rs +++ b/planetwars-server/src/modules/matches.rs @@ -24,15 +24,28 @@ pub struct RunMatch { pub struct MatchPlayer { bot_spec: Box, - // meta that will be passed on to database + // metadata that will be passed on to database code_bundle_id: Option, } impl MatchPlayer { - pub fn from_code_bundle(code_bundle: &db::bots::BotVersion) -> Self { + pub fn from_bot_version(bot: &db::bots::Bot, version: &db::bots::BotVersion) -> Self { MatchPlayer { - bot_spec: code_bundle_to_botspec(code_bundle), - code_bundle_id: Some(code_bundle.id), + bot_spec: bot_version_to_botspec(bot, version), + code_bundle_id: Some(version.id), + } + } + + /// Construct a MatchPlayer from a BotVersion that certainly contains a code bundle path. + /// Will panic when this is not the case. + pub fn from_code_bundle_version(version: &db::bots::BotVersion) -> Self { + let code_bundle_path = version + .code_bundle_path + .as_ref() + .expect("no code_bundle_path found"); + MatchPlayer { + bot_spec: python_docker_bot_spec(code_bundle_path), + code_bundle_id: Some(version.id), } } @@ -97,12 +110,24 @@ impl RunMatch { } } -pub fn code_bundle_to_botspec(code_bundle: &db::bots::BotVersion) -> Box { - // TODO: get rid of this unwrap - let bundle_path = PathBuf::from(BOTS_DIR).join(code_bundle.code_bundle_path.as_ref().unwrap()); +pub fn bot_version_to_botspec( + _bot: &db::bots::Bot, + bot_version: &db::bots::BotVersion, +) -> Box { + if let Some(code_bundle_path) = &bot_version.code_bundle_path { + python_docker_bot_spec(code_bundle_path) + } else if let Some(_container_digest) = &bot_version.container_digest { + unimplemented!() + } else { + panic!("bad bot version") + } +} + +fn python_docker_bot_spec(code_bundle_path: &str) -> Box { + let code_bundle_abs_path = PathBuf::from(BOTS_DIR).join(code_bundle_path); Box::new(DockerBotSpec { - code_path: bundle_path, + code_path: code_bundle_abs_path, image: PYTHON_IMAGE.to_string(), argv: vec!["python".to_string(), "bot.py".to_string()], }) diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs index 751c35e..3182ce2 100644 --- a/planetwars-server/src/modules/ranking.rs +++ b/planetwars-server/src/modules/ranking.rs @@ -37,18 +37,14 @@ pub async fn run_ranker(db_pool: DbPool) { async fn play_ranking_match(selected_bots: Vec, db_pool: DbPool) { let db_conn = db_pool.get().await.expect("could not get db pool"); - let mut code_bundles = Vec::new(); + let mut players = Vec::new(); for bot in &selected_bots { - let code_bundle = db::bots::active_bot_version(bot.id, &db_conn) - .expect("could not get active code bundle"); - code_bundles.push(code_bundle); + let version = db::bots::active_bot_version(bot.id, &db_conn) + .expect("could not get active bot version"); + let player = MatchPlayer::from_bot_version(bot, &version); + players.push(player); } - let players = code_bundles - .iter() - .map(MatchPlayer::from_code_bundle) - .collect::>(); - let mut run_match = RunMatch::from_players(players); run_match .store_in_database(&db_conn) -- cgit v1.2.3 From 0b9a9f0eaafb68acb7896ade26b9ae4508096d5c Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Mon, 11 Jul 2022 20:43:10 +0200 Subject: tying it together: execute docker bots --- planetwars-server/src/modules/matches.rs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/matches.rs b/planetwars-server/src/modules/matches.rs index a8c7ca9..03be5db 100644 --- a/planetwars-server/src/modules/matches.rs +++ b/planetwars-server/src/modules/matches.rs @@ -111,25 +111,36 @@ impl RunMatch { } pub fn bot_version_to_botspec( - _bot: &db::bots::Bot, + bot: &db::bots::Bot, bot_version: &db::bots::BotVersion, ) -> Box { if let Some(code_bundle_path) = &bot_version.code_bundle_path { python_docker_bot_spec(code_bundle_path) - } else if let Some(_container_digest) = &bot_version.container_digest { - unimplemented!() + } else if let Some(container_digest) = &bot_version.container_digest { + // TODO: put this in config + let registry_url = "localhost:9001"; + Box::new(DockerBotSpec { + image: format!("{}/{}@{}", registry_url, bot.name, container_digest), + binds: None, + argv: None, + working_dir: None, + }) } else { panic!("bad bot version") } } fn python_docker_bot_spec(code_bundle_path: &str) -> Box { - let code_bundle_abs_path = PathBuf::from(BOTS_DIR).join(code_bundle_path); + let code_bundle_rel_path = PathBuf::from(BOTS_DIR).join(code_bundle_path); + let code_bundle_abs_path = std::fs::canonicalize(&code_bundle_rel_path).unwrap(); + let code_bundle_path_str = code_bundle_abs_path.as_os_str().to_str().unwrap(); + // TODO: it would be good to simplify this configuration Box::new(DockerBotSpec { - code_path: code_bundle_abs_path, image: PYTHON_IMAGE.to_string(), - argv: vec!["python".to_string(), "bot.py".to_string()], + binds: Some(vec![format!("{}:{}", code_bundle_path_str, "/workdir")]), + argv: Some(vec!["python".to_string(), "bot.py".to_string()]), + working_dir: Some("/workdir".to_string()), }) } -- cgit v1.2.3 From e69bd14f1d64b0d8b2438a40a069d3647c1edd73 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Tue, 12 Jul 2022 20:54:00 +0200 Subject: refactor: delay BotSpec construction in RunMatch --- planetwars-server/src/modules/bot_api.rs | 15 +++++--- planetwars-server/src/modules/matches.rs | 60 ++++++++++++-------------------- planetwars-server/src/modules/ranking.rs | 5 ++- 3 files changed, 36 insertions(+), 44 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index 732aa21..962b33d 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -102,10 +102,10 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { let match_request = req.get_ref(); - let opponent = db::bots::find_bot_by_name(&match_request.opponent_name, &conn) + let opponent_bot = db::bots::find_bot_by_name(&match_request.opponent_name, &conn) .map_err(|_| Status::not_found("opponent not found"))?; - let opponent_code_bundle = db::bots::active_bot_version(opponent.id, &conn) - .map_err(|_| Status::not_found("opponent has no code"))?; + let opponent_bot_version = db::bots::active_bot_version(opponent_bot.id, &conn) + .map_err(|_| Status::not_found("no opponent version found"))?; let player_key = gen_alphanumeric(32); @@ -114,8 +114,13 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { router: self.router.clone(), }); let mut run_match = RunMatch::from_players(vec![ - MatchPlayer::from_bot_spec(remote_bot_spec), - MatchPlayer::from_bot_version(&opponent, &opponent_code_bundle), + MatchPlayer::BotSpec { + spec: remote_bot_spec, + }, + MatchPlayer::BotVersion { + bot: Some(opponent_bot), + version: opponent_bot_version, + }, ]); let created_match = run_match .store_in_database(&conn) diff --git a/planetwars-server/src/modules/matches.rs b/planetwars-server/src/modules/matches.rs index 03be5db..0496db7 100644 --- a/planetwars-server/src/modules/matches.rs +++ b/planetwars-server/src/modules/matches.rs @@ -22,39 +22,14 @@ pub struct RunMatch { match_id: Option, } -pub struct MatchPlayer { - bot_spec: Box, - // metadata that will be passed on to database - code_bundle_id: Option, -} - -impl MatchPlayer { - pub fn from_bot_version(bot: &db::bots::Bot, version: &db::bots::BotVersion) -> Self { - MatchPlayer { - bot_spec: bot_version_to_botspec(bot, version), - code_bundle_id: Some(version.id), - } - } - - /// Construct a MatchPlayer from a BotVersion that certainly contains a code bundle path. - /// Will panic when this is not the case. - pub fn from_code_bundle_version(version: &db::bots::BotVersion) -> Self { - let code_bundle_path = version - .code_bundle_path - .as_ref() - .expect("no code_bundle_path found"); - MatchPlayer { - bot_spec: python_docker_bot_spec(code_bundle_path), - code_bundle_id: Some(version.id), - } - } - - pub fn from_bot_spec(bot_spec: Box) -> Self { - MatchPlayer { - bot_spec, - code_bundle_id: None, - } - } +pub enum MatchPlayer { + BotVersion { + bot: Option, + version: db::bots::BotVersion, + }, + BotSpec { + spec: Box, + }, } impl RunMatch { @@ -76,7 +51,12 @@ impl RunMatch { .players .into_iter() .map(|player| runner::MatchPlayer { - bot_spec: player.bot_spec, + bot_spec: match player { + MatchPlayer::BotVersion { bot, version } => { + bot_version_to_botspec(bot.as_ref(), &version) + } + MatchPlayer::BotSpec { spec } => spec, + }, }) .collect(), } @@ -94,11 +74,14 @@ impl RunMatch { .players .iter() .map(|p| db::matches::MatchPlayerData { - code_bundle_id: p.code_bundle_id, + code_bundle_id: match p { + MatchPlayer::BotVersion { version, .. } => Some(version.id), + MatchPlayer::BotSpec { .. } => None, + }, }) .collect::>(); - let match_data = db::matches::create_match(&new_match_data, &new_match_players, &db_conn)?; + let match_data = db::matches::create_match(&new_match_data, &new_match_players, db_conn)?; self.match_id = Some(match_data.base.id); Ok(match_data) } @@ -111,12 +94,12 @@ impl RunMatch { } pub fn bot_version_to_botspec( - bot: &db::bots::Bot, + bot: Option<&db::bots::Bot>, bot_version: &db::bots::BotVersion, ) -> Box { if let Some(code_bundle_path) = &bot_version.code_bundle_path { python_docker_bot_spec(code_bundle_path) - } else if let Some(container_digest) = &bot_version.container_digest { + } else if let (Some(container_digest), Some(bot)) = (&bot_version.container_digest, bot) { // TODO: put this in config let registry_url = "localhost:9001"; Box::new(DockerBotSpec { @@ -126,6 +109,7 @@ pub fn bot_version_to_botspec( working_dir: None, }) } else { + // TODO: ideally this would not be possible panic!("bad bot version") } } diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs index 3182ce2..7147b98 100644 --- a/planetwars-server/src/modules/ranking.rs +++ b/planetwars-server/src/modules/ranking.rs @@ -41,7 +41,10 @@ async fn play_ranking_match(selected_bots: Vec, db_pool: DbPool) { for bot in &selected_bots { let version = db::bots::active_bot_version(bot.id, &db_conn) .expect("could not get active bot version"); - let player = MatchPlayer::from_bot_version(bot, &version); + let player = MatchPlayer::BotVersion { + bot: Some(bot.clone()), + version, + }; players.push(player); } -- cgit v1.2.3 From 668409e76d8cc7797fe627b2e2c3d0223b3db684 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Wed, 13 Jul 2022 19:36:07 +0200 Subject: refactor: unify match save and spawn --- planetwars-server/src/modules/bot_api.rs | 8 ++++---- planetwars-server/src/modules/matches.rs | 32 ++++++++++++++++++-------------- planetwars-server/src/modules/ranking.rs | 12 +++++------- 3 files changed, 27 insertions(+), 25 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index 962b33d..0ee9357 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -122,10 +122,10 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { version: opponent_bot_version, }, ]); - let created_match = run_match - .store_in_database(&conn) - .expect("failed to save match"); - run_match.spawn(self.conn_pool.clone()); + let (created_match, _) = run_match + .run(self.conn_pool.clone()) + .await + .expect("failed to create match"); Ok(Response::new(pb::CreatedMatch { match_id: created_match.base.id, diff --git a/planetwars-server/src/modules/matches.rs b/planetwars-server/src/modules/matches.rs index 0496db7..6caa8c2 100644 --- a/planetwars-server/src/modules/matches.rs +++ b/planetwars-server/src/modules/matches.rs @@ -19,7 +19,6 @@ const PYTHON_IMAGE: &str = "python:3.10-slim-buster"; pub struct RunMatch { log_file_name: String, players: Vec, - match_id: Option, } pub enum MatchPlayer { @@ -38,7 +37,6 @@ impl RunMatch { RunMatch { log_file_name, players, - match_id: None, } } @@ -62,10 +60,24 @@ impl RunMatch { } } - pub fn store_in_database(&mut self, db_conn: &PgConnection) -> QueryResult { - // don't store the same match twice - assert!(self.match_id.is_none()); + pub async fn run( + self, + conn_pool: ConnectionPool, + ) -> QueryResult<(MatchData, JoinHandle)> { + let match_data = { + // TODO: it would be nice to get an already-open connection here when possible. + // Maybe we need an additional abstraction, bundling a connection and connection pool? + let db_conn = conn_pool.get().await.expect("could not get a connection"); + self.store_in_database(&db_conn)? + }; + let runner_config = self.into_runner_config(); + let handle = tokio::spawn(run_match_task(conn_pool, runner_config, match_data.base.id)); + + Ok((match_data, handle)) + } + + fn store_in_database(&self, db_conn: &PgConnection) -> QueryResult { let new_match_data = db::matches::NewMatch { state: db::matches::MatchState::Playing, log_path: &self.log_file_name, @@ -81,15 +93,7 @@ impl RunMatch { }) .collect::>(); - let match_data = db::matches::create_match(&new_match_data, &new_match_players, db_conn)?; - self.match_id = Some(match_data.base.id); - Ok(match_data) - } - - pub fn spawn(self, pool: ConnectionPool) -> JoinHandle { - let match_id = self.match_id.expect("match must be saved before running"); - let runner_config = self.into_runner_config(); - tokio::spawn(run_match_task(pool, runner_config, match_id)) + db::matches::create_match(&new_match_data, &new_match_players, db_conn) } } diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs index 7147b98..1c35394 100644 --- a/planetwars-server/src/modules/ranking.rs +++ b/planetwars-server/src/modules/ranking.rs @@ -48,14 +48,12 @@ async fn play_ranking_match(selected_bots: Vec, db_pool: DbPool) { players.push(player); } - let mut run_match = RunMatch::from_players(players); - run_match - .store_in_database(&db_conn) - .expect("could not store match in db"); - run_match - .spawn(db_pool.clone()) + let (_, handle) = RunMatch::from_players(players) + .run(db_pool.clone()) .await - .expect("running match failed"); + .expect("failed to run match"); + // wait for match to complete, so that only one ranking match can be running + let _outcome = handle.await; } fn recalculate_ratings(db_conn: &PgConnection) -> QueryResult<()> { -- cgit v1.2.3 From 00459f9e3d818f0fb84160862f02898d64f98110 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Thu, 14 Jul 2022 20:53:08 +0200 Subject: create a configuration to hold docker registry url --- planetwars-server/src/modules/bot_api.rs | 29 ++++++++++++++++------------ planetwars-server/src/modules/matches.rs | 33 +++++++++++++++++++++----------- planetwars-server/src/modules/ranking.rs | 15 +++++++++++---- 3 files changed, 50 insertions(+), 27 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index 0ee9357..4e7d737 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -21,10 +21,11 @@ use crate::db; use crate::util::gen_alphanumeric; use crate::ConnectionPool; -use super::matches::{MatchPlayer, RunMatch}; +use super::matches::{MatchPlayer, MatchRunnerConfig, RunMatch}; pub struct BotApiServer { conn_pool: ConnectionPool, + runner_config: Arc, router: PlayerRouter, } @@ -113,15 +114,18 @@ impl pb::bot_api_service_server::BotApiService for BotApiServer { player_key: player_key.clone(), router: self.router.clone(), }); - let mut run_match = RunMatch::from_players(vec![ - MatchPlayer::BotSpec { - spec: remote_bot_spec, - }, - MatchPlayer::BotVersion { - bot: Some(opponent_bot), - version: opponent_bot_version, - }, - ]); + let run_match = RunMatch::from_players( + self.runner_config.clone(), + vec![ + MatchPlayer::BotSpec { + spec: remote_bot_spec, + }, + MatchPlayer::BotVersion { + bot: Some(opponent_bot), + version: opponent_bot_version, + }, + ], + ); let (created_match, _) = run_match .run(self.conn_pool.clone()) .await @@ -261,11 +265,12 @@ async fn schedule_timeout( .resolve_request(request_id, Err(RequestError::Timeout)); } -pub async fn run_bot_api(pool: ConnectionPool) { +pub async fn run_bot_api(runner_config: Arc, pool: ConnectionPool) { let router = PlayerRouter::new(); let server = BotApiServer { router, - conn_pool: pool.clone(), + conn_pool: pool, + runner_config, }; let addr = SocketAddr::from(([127, 0, 0, 1], 50051)); diff --git a/planetwars-server/src/modules/matches.rs b/planetwars-server/src/modules/matches.rs index 6caa8c2..07dc68b 100644 --- a/planetwars-server/src/modules/matches.rs +++ b/planetwars-server/src/modules/matches.rs @@ -1,4 +1,4 @@ -use std::path::PathBuf; +use std::{path::PathBuf, sync::Arc}; use diesel::{PgConnection, QueryResult}; use planetwars_matchrunner::{self as runner, docker_runner::DockerBotSpec, BotSpec, MatchConfig}; @@ -14,11 +14,16 @@ use crate::{ ConnectionPool, BOTS_DIR, MAPS_DIR, MATCHES_DIR, }; -const PYTHON_IMAGE: &str = "python:3.10-slim-buster"; +// TODO: add all paths +pub struct MatchRunnerConfig { + pub python_runner_image: String, + pub container_registry_url: String, +} pub struct RunMatch { log_file_name: String, players: Vec, + runner_config: Arc, } pub enum MatchPlayer { @@ -32,15 +37,16 @@ pub enum MatchPlayer { } impl RunMatch { - pub fn from_players(players: Vec) -> Self { + pub fn from_players(runner_config: Arc, players: Vec) -> Self { let log_file_name = format!("{}.log", gen_alphanumeric(16)); RunMatch { + runner_config, log_file_name, players, } } - pub fn into_runner_config(self) -> runner::MatchConfig { + fn into_runner_config(self) -> runner::MatchConfig { runner::MatchConfig { map_path: PathBuf::from(MAPS_DIR).join("hex.json"), map_name: "hex".to_string(), @@ -51,7 +57,7 @@ impl RunMatch { .map(|player| runner::MatchPlayer { bot_spec: match player { MatchPlayer::BotVersion { bot, version } => { - bot_version_to_botspec(bot.as_ref(), &version) + bot_version_to_botspec(&self.runner_config, bot.as_ref(), &version) } MatchPlayer::BotSpec { spec } => spec, }, @@ -98,16 +104,18 @@ impl RunMatch { } pub fn bot_version_to_botspec( + runner_config: &Arc, bot: Option<&db::bots::Bot>, bot_version: &db::bots::BotVersion, ) -> Box { if let Some(code_bundle_path) = &bot_version.code_bundle_path { - python_docker_bot_spec(code_bundle_path) + python_docker_bot_spec(runner_config, code_bundle_path) } else if let (Some(container_digest), Some(bot)) = (&bot_version.container_digest, bot) { - // TODO: put this in config - let registry_url = "localhost:9001"; Box::new(DockerBotSpec { - image: format!("{}/{}@{}", registry_url, bot.name, container_digest), + image: format!( + "{}/{}@{}", + runner_config.container_registry_url, bot.name, container_digest + ), binds: None, argv: None, working_dir: None, @@ -118,14 +126,17 @@ pub fn bot_version_to_botspec( } } -fn python_docker_bot_spec(code_bundle_path: &str) -> Box { +fn python_docker_bot_spec( + runner_config: &Arc, + code_bundle_path: &str, +) -> Box { let code_bundle_rel_path = PathBuf::from(BOTS_DIR).join(code_bundle_path); let code_bundle_abs_path = std::fs::canonicalize(&code_bundle_rel_path).unwrap(); let code_bundle_path_str = code_bundle_abs_path.as_os_str().to_str().unwrap(); // TODO: it would be good to simplify this configuration Box::new(DockerBotSpec { - image: PYTHON_IMAGE.to_string(), + image: runner_config.python_runner_image.clone(), binds: Some(vec![format!("{}:{}", code_bundle_path_str, "/workdir")]), argv: Some(vec!["python".to_string(), "bot.py".to_string()]), working_dir: Some("/workdir".to_string()), diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs index 1c35394..e483d1c 100644 --- a/planetwars-server/src/modules/ranking.rs +++ b/planetwars-server/src/modules/ranking.rs @@ -6,12 +6,15 @@ use diesel::{PgConnection, QueryResult}; use rand::seq::SliceRandom; use std::collections::HashMap; use std::mem; +use std::sync::Arc; use std::time::{Duration, Instant}; use tokio; +use super::matches::MatchRunnerConfig; + const RANKER_INTERVAL: u64 = 60; -pub async fn run_ranker(db_pool: DbPool) { +pub async fn run_ranker(runner_config: Arc, db_pool: DbPool) { // TODO: make this configurable // play at most one match every n seconds let mut interval = tokio::time::interval(Duration::from_secs(RANKER_INTERVAL)); @@ -30,12 +33,16 @@ pub async fn run_ranker(db_pool: DbPool) { let mut rng = &mut rand::thread_rng(); bots.choose_multiple(&mut rng, 2).cloned().collect() }; - play_ranking_match(selected_bots, db_pool.clone()).await; + play_ranking_match(runner_config.clone(), selected_bots, db_pool.clone()).await; recalculate_ratings(&db_conn).expect("could not recalculate ratings"); } } -async fn play_ranking_match(selected_bots: Vec, db_pool: DbPool) { +async fn play_ranking_match( + runner_config: Arc, + selected_bots: Vec, + db_pool: DbPool, +) { let db_conn = db_pool.get().await.expect("could not get db pool"); let mut players = Vec::new(); for bot in &selected_bots { @@ -48,7 +55,7 @@ async fn play_ranking_match(selected_bots: Vec, db_pool: DbPool) { players.push(player); } - let (_, handle) = RunMatch::from_players(players) + let (_, handle) = RunMatch::from_players(runner_config, players) .run(db_pool.clone()) .await .expect("failed to run match"); -- cgit v1.2.3 From ec5c91d37b46cb3cec4878176469c66d2304dadd Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Thu, 14 Jul 2022 21:50:42 +0200 Subject: change runnerconfig to globalconfig --- planetwars-server/src/modules/bot_api.rs | 7 ++++--- planetwars-server/src/modules/matches.rs | 16 +++++----------- planetwars-server/src/modules/ranking.rs | 16 +++++----------- 3 files changed, 14 insertions(+), 25 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bot_api.rs b/planetwars-server/src/modules/bot_api.rs index 4e7d737..33f5d87 100644 --- a/planetwars-server/src/modules/bot_api.rs +++ b/planetwars-server/src/modules/bot_api.rs @@ -20,12 +20,13 @@ use planetwars_matchrunner as runner; use crate::db; use crate::util::gen_alphanumeric; use crate::ConnectionPool; +use crate::GlobalConfig; -use super::matches::{MatchPlayer, MatchRunnerConfig, RunMatch}; +use super::matches::{MatchPlayer, RunMatch}; pub struct BotApiServer { conn_pool: ConnectionPool, - runner_config: Arc, + runner_config: Arc, router: PlayerRouter, } @@ -265,7 +266,7 @@ async fn schedule_timeout( .resolve_request(request_id, Err(RequestError::Timeout)); } -pub async fn run_bot_api(runner_config: Arc, pool: ConnectionPool) { +pub async fn run_bot_api(runner_config: Arc, pool: ConnectionPool) { let router = PlayerRouter::new(); let server = BotApiServer { router, diff --git a/planetwars-server/src/modules/matches.rs b/planetwars-server/src/modules/matches.rs index 07dc68b..dd5e523 100644 --- a/planetwars-server/src/modules/matches.rs +++ b/planetwars-server/src/modules/matches.rs @@ -11,19 +11,13 @@ use crate::{ matches::{MatchData, MatchResult}, }, util::gen_alphanumeric, - ConnectionPool, BOTS_DIR, MAPS_DIR, MATCHES_DIR, + ConnectionPool, GlobalConfig, BOTS_DIR, MAPS_DIR, MATCHES_DIR, }; -// TODO: add all paths -pub struct MatchRunnerConfig { - pub python_runner_image: String, - pub container_registry_url: String, -} - pub struct RunMatch { log_file_name: String, players: Vec, - runner_config: Arc, + runner_config: Arc, } pub enum MatchPlayer { @@ -37,7 +31,7 @@ pub enum MatchPlayer { } impl RunMatch { - pub fn from_players(runner_config: Arc, players: Vec) -> Self { + pub fn from_players(runner_config: Arc, players: Vec) -> Self { let log_file_name = format!("{}.log", gen_alphanumeric(16)); RunMatch { runner_config, @@ -104,7 +98,7 @@ impl RunMatch { } pub fn bot_version_to_botspec( - runner_config: &Arc, + runner_config: &Arc, bot: Option<&db::bots::Bot>, bot_version: &db::bots::BotVersion, ) -> Box { @@ -127,7 +121,7 @@ pub fn bot_version_to_botspec( } fn python_docker_bot_spec( - runner_config: &Arc, + runner_config: &Arc, code_bundle_path: &str, ) -> Box { let code_bundle_rel_path = PathBuf::from(BOTS_DIR).join(code_bundle_path); diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs index e483d1c..a9f6419 100644 --- a/planetwars-server/src/modules/ranking.rs +++ b/planetwars-server/src/modules/ranking.rs @@ -1,4 +1,4 @@ -use crate::{db::bots::Bot, DbPool}; +use crate::{db::bots::Bot, DbPool, GlobalConfig}; use crate::db; use crate::modules::matches::{MatchPlayer, RunMatch}; @@ -10,11 +10,9 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use tokio; -use super::matches::MatchRunnerConfig; - const RANKER_INTERVAL: u64 = 60; -pub async fn run_ranker(runner_config: Arc, db_pool: DbPool) { +pub async fn run_ranker(config: Arc, db_pool: DbPool) { // TODO: make this configurable // play at most one match every n seconds let mut interval = tokio::time::interval(Duration::from_secs(RANKER_INTERVAL)); @@ -33,16 +31,12 @@ pub async fn run_ranker(runner_config: Arc, db_pool: DbPool) let mut rng = &mut rand::thread_rng(); bots.choose_multiple(&mut rng, 2).cloned().collect() }; - play_ranking_match(runner_config.clone(), selected_bots, db_pool.clone()).await; + play_ranking_match(config.clone(), selected_bots, db_pool.clone()).await; recalculate_ratings(&db_conn).expect("could not recalculate ratings"); } } -async fn play_ranking_match( - runner_config: Arc, - selected_bots: Vec, - db_pool: DbPool, -) { +async fn play_ranking_match(config: Arc, selected_bots: Vec, db_pool: DbPool) { let db_conn = db_pool.get().await.expect("could not get db pool"); let mut players = Vec::new(); for bot in &selected_bots { @@ -55,7 +49,7 @@ async fn play_ranking_match( players.push(player); } - let (_, handle) = RunMatch::from_players(runner_config, players) + let (_, handle) = RunMatch::from_players(config, players) .run(db_pool.clone()) .await .expect("failed to run match"); -- cgit v1.2.3 From d13d131130ab53fb8ee7d49d2b40718622a4ab11 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sat, 16 Jul 2022 21:22:03 +0200 Subject: move storage paths to GlobalConfig --- planetwars-server/src/modules/bots.rs | 5 +++-- planetwars-server/src/modules/matches.rs | 25 +++++++++++-------------- 2 files changed, 14 insertions(+), 16 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/bots.rs b/planetwars-server/src/modules/bots.rs index b82ad41..5513539 100644 --- a/planetwars-server/src/modules/bots.rs +++ b/planetwars-server/src/modules/bots.rs @@ -2,17 +2,18 @@ use std::path::PathBuf; use diesel::{PgConnection, QueryResult}; -use crate::{db, util::gen_alphanumeric, BOTS_DIR}; +use crate::{db, util::gen_alphanumeric, GlobalConfig}; /// Save a string containing bot code as a code bundle. pub fn save_code_string( bot_code: &str, bot_id: Option, conn: &PgConnection, + config: &GlobalConfig, ) -> QueryResult { let bundle_name = gen_alphanumeric(16); - let code_bundle_dir = PathBuf::from(BOTS_DIR).join(&bundle_name); + let code_bundle_dir = PathBuf::from(&config.bots_directory).join(&bundle_name); std::fs::create_dir(&code_bundle_dir).unwrap(); std::fs::write(code_bundle_dir.join("bot.py"), bot_code).unwrap(); diff --git a/planetwars-server/src/modules/matches.rs b/planetwars-server/src/modules/matches.rs index dd5e523..a1fe63d 100644 --- a/planetwars-server/src/modules/matches.rs +++ b/planetwars-server/src/modules/matches.rs @@ -11,13 +11,13 @@ use crate::{ matches::{MatchData, MatchResult}, }, util::gen_alphanumeric, - ConnectionPool, GlobalConfig, BOTS_DIR, MAPS_DIR, MATCHES_DIR, + ConnectionPool, GlobalConfig, }; pub struct RunMatch { log_file_name: String, players: Vec, - runner_config: Arc, + config: Arc, } pub enum MatchPlayer { @@ -31,10 +31,10 @@ pub enum MatchPlayer { } impl RunMatch { - pub fn from_players(runner_config: Arc, players: Vec) -> Self { + pub fn from_players(config: Arc, players: Vec) -> Self { let log_file_name = format!("{}.log", gen_alphanumeric(16)); RunMatch { - runner_config, + config, log_file_name, players, } @@ -42,16 +42,16 @@ impl RunMatch { fn into_runner_config(self) -> runner::MatchConfig { runner::MatchConfig { - map_path: PathBuf::from(MAPS_DIR).join("hex.json"), + map_path: PathBuf::from(&self.config.maps_directory).join("hex.json"), map_name: "hex".to_string(), - log_path: PathBuf::from(MATCHES_DIR).join(&self.log_file_name), + log_path: PathBuf::from(&self.config.match_logs_directory).join(&self.log_file_name), players: self .players .into_iter() .map(|player| runner::MatchPlayer { bot_spec: match player { MatchPlayer::BotVersion { bot, version } => { - bot_version_to_botspec(&self.runner_config, bot.as_ref(), &version) + bot_version_to_botspec(&self.config, bot.as_ref(), &version) } MatchPlayer::BotSpec { spec } => spec, }, @@ -98,7 +98,7 @@ impl RunMatch { } pub fn bot_version_to_botspec( - runner_config: &Arc, + runner_config: &GlobalConfig, bot: Option<&db::bots::Bot>, bot_version: &db::bots::BotVersion, ) -> Box { @@ -120,17 +120,14 @@ pub fn bot_version_to_botspec( } } -fn python_docker_bot_spec( - runner_config: &Arc, - code_bundle_path: &str, -) -> Box { - let code_bundle_rel_path = PathBuf::from(BOTS_DIR).join(code_bundle_path); +fn python_docker_bot_spec(config: &GlobalConfig, code_bundle_path: &str) -> Box { + let code_bundle_rel_path = PathBuf::from(&config.bots_directory).join(code_bundle_path); let code_bundle_abs_path = std::fs::canonicalize(&code_bundle_rel_path).unwrap(); let code_bundle_path_str = code_bundle_abs_path.as_os_str().to_str().unwrap(); // TODO: it would be good to simplify this configuration Box::new(DockerBotSpec { - image: runner_config.python_runner_image.clone(), + image: config.python_runner_image.clone(), binds: Some(vec![format!("{}:{}", code_bundle_path_str, "/workdir")]), argv: Some(vec!["python".to_string(), "bot.py".to_string()]), working_dir: Some("/workdir".to_string()), -- cgit v1.2.3 From 0cf7b5299d1085e32760ae9843625724a09c8c29 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sat, 16 Jul 2022 21:47:22 +0200 Subject: integrate registry with GlobalConfig --- planetwars-server/src/modules/registry.rs | 57 +++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 18 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/registry.rs b/planetwars-server/src/modules/registry.rs index 7198a61..3f6dad2 100644 --- a/planetwars-server/src/modules/registry.rs +++ b/planetwars-server/src/modules/registry.rs @@ -6,24 +6,22 @@ use axum::headers::authorization::Basic; use axum::headers::Authorization; use axum::response::{IntoResponse, Response}; use axum::routing::{get, head, post, put}; -use axum::{async_trait, Router}; +use axum::{async_trait, Extension, Router}; use futures::StreamExt; use hyper::StatusCode; use serde::Serialize; use sha2::{Digest, Sha256}; use std::path::PathBuf; +use std::sync::Arc; use tokio::io::AsyncWriteExt; use tokio_util::io::ReaderStream; use crate::db::bots::NewBotVersion; use crate::util::gen_alphanumeric; -use crate::{db, DatabaseConnection}; +use crate::{db, DatabaseConnection, GlobalConfig}; use crate::db::users::{authenticate_user, Credentials, User}; -// TODO: put this in a config file -const REGISTRY_PATH: &str = "./data/registry"; - pub fn registry_service() -> Router { Router::new() // The docker API requires this trailing slash @@ -49,8 +47,6 @@ fn registry_api_v2() -> Router { } const ADMIN_USERNAME: &str = "admin"; -// TODO: put this in some configuration -const ADMIN_PASSWORD: &str = "supersecretpassword"; type AuthorizationHeader = TypedHeader>; @@ -105,8 +101,12 @@ where password: basic.password(), }; + let Extension(config) = Extension::>::from_request(req) + .await + .unwrap(); + if credentials.username == ADMIN_USERNAME { - if credentials.password == ADMIN_PASSWORD { + if credentials.password == config.registry_admin_password { Ok(RegistryAuth::Admin) } else { Err(RegistryAuthError::InvalidCredentials) @@ -162,11 +162,14 @@ async fn check_blob_exists( db_conn: DatabaseConnection, auth: RegistryAuth, Path((repository_name, raw_digest)): Path<(String, String)>, + Extension(config): Extension>, ) -> Result { check_access(&repository_name, &auth, &db_conn)?; let digest = raw_digest.strip_prefix("sha256:").unwrap(); - let blob_path = PathBuf::from(REGISTRY_PATH).join("sha256").join(&digest); + let blob_path = PathBuf::from(&config.registry_directory) + .join("sha256") + .join(&digest); if blob_path.exists() { let metadata = std::fs::metadata(&blob_path).unwrap(); Ok((StatusCode::OK, [("Content-Length", metadata.len())])) @@ -179,11 +182,14 @@ async fn get_blob( db_conn: DatabaseConnection, auth: RegistryAuth, Path((repository_name, raw_digest)): Path<(String, String)>, + Extension(config): Extension>, ) -> Result { check_access(&repository_name, &auth, &db_conn)?; let digest = raw_digest.strip_prefix("sha256:").unwrap(); - let blob_path = PathBuf::from(REGISTRY_PATH).join("sha256").join(&digest); + let blob_path = PathBuf::from(&config.registry_directory) + .join("sha256") + .join(&digest); if !blob_path.exists() { return Err(StatusCode::NOT_FOUND); } @@ -197,13 +203,18 @@ async fn create_upload( db_conn: DatabaseConnection, auth: RegistryAuth, Path(repository_name): Path, + Extension(config): Extension>, ) -> Result { check_access(&repository_name, &auth, &db_conn)?; let uuid = gen_alphanumeric(16); - tokio::fs::File::create(PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid)) - .await - .unwrap(); + tokio::fs::File::create( + PathBuf::from(&config.registry_directory) + .join("uploads") + .join(&uuid), + ) + .await + .unwrap(); Ok(Response::builder() .status(StatusCode::ACCEPTED) @@ -222,11 +233,14 @@ async fn patch_upload( auth: RegistryAuth, Path((repository_name, uuid)): Path<(String, String)>, mut stream: BodyStream, + Extension(config): Extension>, ) -> Result { check_access(&repository_name, &auth, &db_conn)?; // TODO: support content range header in request - let upload_path = PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid); + let upload_path = PathBuf::from(&config.registry_directory) + .join("uploads") + .join(&uuid); let mut file = tokio::fs::OpenOptions::new() .read(false) .write(true) @@ -266,10 +280,13 @@ async fn put_upload( Path((repository_name, uuid)): Path<(String, String)>, Query(params): Query, mut stream: BodyStream, + Extension(config): Extension>, ) -> Result { check_access(&repository_name, &auth, &db_conn)?; - let upload_path = PathBuf::from(REGISTRY_PATH).join("uploads").join(&uuid); + let upload_path = PathBuf::from(&config.registry_directory) + .join("uploads") + .join(&uuid); let mut file = tokio::fs::OpenOptions::new() .read(false) .write(true) @@ -293,7 +310,9 @@ async fn put_upload( return Err(StatusCode::BAD_REQUEST); } - let target_path = PathBuf::from(REGISTRY_PATH).join("sha256").join(&digest); + let target_path = PathBuf::from(&config.registry_directory) + .join("sha256") + .join(&digest); tokio::fs::rename(&upload_path, &target_path).await.unwrap(); Ok(Response::builder() @@ -314,10 +333,11 @@ async fn get_manifest( db_conn: DatabaseConnection, auth: RegistryAuth, Path((repository_name, reference)): Path<(String, String)>, + Extension(config): Extension>, ) -> Result { check_access(&repository_name, &auth, &db_conn)?; - let manifest_path = PathBuf::from(REGISTRY_PATH) + let manifest_path = PathBuf::from(&config.registry_directory) .join("manifests") .join(&repository_name) .join(&reference) @@ -339,10 +359,11 @@ async fn put_manifest( auth: RegistryAuth, Path((repository_name, reference)): Path<(String, String)>, mut stream: BodyStream, + Extension(config): Extension>, ) -> Result { let bot = check_access(&repository_name, &auth, &db_conn)?; - let repository_dir = PathBuf::from(REGISTRY_PATH) + let repository_dir = PathBuf::from(&config.registry_directory) .join("manifests") .join(&repository_name); -- cgit v1.2.3