From e7da88c6a5135e78acea3a29040cfbf1e7e0b71f Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Wed, 27 Apr 2022 20:43:12 +0200 Subject: restructure server entrypoint for ranker --- planetwars-server/src/modules/mod.rs | 1 + planetwars-server/src/modules/ranking.rs | 5 +++++ 2 files changed, 6 insertions(+) create mode 100644 planetwars-server/src/modules/ranking.rs (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/mod.rs b/planetwars-server/src/modules/mod.rs index 57c1ef5..2efce4e 100644 --- a/planetwars-server/src/modules/mod.rs +++ b/planetwars-server/src/modules/mod.rs @@ -1,3 +1,4 @@ // This module implements general domain logic, not directly // tied to the database or API layers. pub mod bots; +pub mod ranking; diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs new file mode 100644 index 0000000..739e6a6 --- /dev/null +++ b/planetwars-server/src/modules/ranking.rs @@ -0,0 +1,5 @@ +use crate::DbPool; + +pub async fn run_ranker(_db_pool: DbPool) { + // do nothing, for now +} -- cgit v1.2.3 From 7b142554d808a494df4ba9e616c58861370ccd93 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Thu, 28 Apr 2022 21:31:49 +0200 Subject: move match running logic to separate module --- planetwars-server/src/modules/matches.rs | 102 +++++++++++++++++++++++++++++++ planetwars-server/src/modules/mod.rs | 1 + planetwars-server/src/modules/ranking.rs | 33 +++++++++- 3 files changed, 133 insertions(+), 3 deletions(-) create mode 100644 planetwars-server/src/modules/matches.rs (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/matches.rs b/planetwars-server/src/modules/matches.rs new file mode 100644 index 0000000..201c6d4 --- /dev/null +++ b/planetwars-server/src/modules/matches.rs @@ -0,0 +1,102 @@ +use std::path::PathBuf; + +use diesel::{PgConnection, QueryResult}; +use planetwars_matchrunner::{self as runner, docker_runner::DockerBotSpec, BotSpec, MatchConfig}; +use runner::MatchOutcome; +use tokio::task::JoinHandle; + +use crate::{ + db::{self, matches::MatchData}, + util::gen_alphanumeric, + ConnectionPool, BOTS_DIR, MAPS_DIR, MATCHES_DIR, +}; + +const PYTHON_IMAGE: &str = "python:3.10-slim-buster"; + +pub struct RunMatch<'a> { + log_file_name: String, + player_code_bundles: Vec<&'a db::bots::CodeBundle>, + match_id: Option, +} + +impl<'a> RunMatch<'a> { + pub fn from_players(player_code_bundles: Vec<&'a db::bots::CodeBundle>) -> Self { + let log_file_name = format!("{}.log", gen_alphanumeric(16)); + RunMatch { + log_file_name, + player_code_bundles, + match_id: None, + } + } + + pub fn 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), + }) + .collect(), + } + } + + pub fn store_in_database(&mut self, db_conn: &PgConnection) -> QueryResult { + // don't store the same match twice + assert!(self.match_id.is_none()); + + let new_match_data = db::matches::NewMatch { + state: db::matches::MatchState::Playing, + log_path: &self.log_file_name, + }; + let new_match_players = self + .player_code_bundles + .iter() + .map(|b| db::matches::MatchPlayerData { + code_bundle_id: b.id, + }) + .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.runner_config(); + tokio::spawn(run_match_task(pool, runner_config, match_id)) + } +} + +pub fn code_bundle_to_botspec(code_bundle: &db::bots::CodeBundle) -> Box { + let bundle_path = PathBuf::from(BOTS_DIR).join(&code_bundle.path); + + Box::new(DockerBotSpec { + code_path: bundle_path, + image: PYTHON_IMAGE.to_string(), + argv: vec!["python".to_string(), "bot.py".to_string()], + }) +} + +async fn run_match_task( + connection_pool: ConnectionPool, + match_config: MatchConfig, + match_id: i32, +) -> MatchOutcome { + let outcome = runner::run_match(match_config).await; + + // update match state in database + let conn = connection_pool + .get() + .await + .expect("could not get database connection"); + + db::matches::set_match_state(match_id, db::matches::MatchState::Finished, &conn) + .expect("could not update match state"); + + return outcome; +} diff --git a/planetwars-server/src/modules/mod.rs b/planetwars-server/src/modules/mod.rs index 2efce4e..bea28e0 100644 --- a/planetwars-server/src/modules/mod.rs +++ b/planetwars-server/src/modules/mod.rs @@ -1,4 +1,5 @@ // This module implements general domain logic, not directly // tied to the database or API layers. pub mod bots; +pub mod matches; pub mod ranking; diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs index 739e6a6..53e1e4e 100644 --- a/planetwars-server/src/modules/ranking.rs +++ b/planetwars-server/src/modules/ranking.rs @@ -1,5 +1,32 @@ -use crate::DbPool; +use crate::{db::bots::Bot, DbPool}; -pub async fn run_ranker(_db_pool: DbPool) { - // do nothing, for now +use crate::db; +use diesel::PgConnection; +use rand::seq::SliceRandom; +use std::time::Duration; +use tokio; + +pub async fn run_ranker(db_pool: DbPool) { + // TODO: make this configurable + // play at most one match every n seconds + let mut interval = tokio::time::interval(Duration::from_secs(10)); + let db_conn = db_pool + .get() + .await + .expect("could not get database connection"); + loop { + interval.tick().await; + let bots = db::bots::find_all_bots(&db_conn).unwrap(); + if bots.len() < 2 { + // not enough bots to play a match + continue; + } + let selected_bots: Vec = { + let mut rng = &mut rand::thread_rng(); + bots.choose_multiple(&mut rng, 2).cloned().collect() + }; + play_match(selected_bots, db_pool.clone()).await; + } } + +async fn play_match(selected_bots: Vec, db_pool: DbPool) {} -- cgit v1.2.3 From 06ac7a370ce763c2f997b9606ca880bf3782f926 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Tue, 17 May 2022 21:57:44 +0200 Subject: implement simple elo rating --- planetwars-server/src/modules/ranking.rs | 63 ++++++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 4 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs index 53e1e4e..3892383 100644 --- a/planetwars-server/src/modules/ranking.rs +++ b/planetwars-server/src/modules/ranking.rs @@ -1,15 +1,20 @@ use crate::{db::bots::Bot, DbPool}; use crate::db; -use diesel::PgConnection; +use crate::modules::matches::RunMatch; use rand::seq::SliceRandom; use std::time::Duration; use tokio; +const RANKER_INTERVAL: u64 = 60; +const START_RATING: f64 = 0.0; +const SCALE: f64 = 100.0; +const MAX_UPDATE: f64 = 5.0; + pub async fn run_ranker(db_pool: DbPool) { // TODO: make this configurable // play at most one match every n seconds - let mut interval = tokio::time::interval(Duration::from_secs(10)); + let mut interval = tokio::time::interval(Duration::from_secs(RANKER_INTERVAL)); let db_conn = db_pool .get() .await @@ -25,8 +30,58 @@ pub async fn run_ranker(db_pool: DbPool) { let mut rng = &mut rand::thread_rng(); bots.choose_multiple(&mut rng, 2).cloned().collect() }; - play_match(selected_bots, db_pool.clone()).await; + play_ranking_match(selected_bots, db_pool.clone()).await; } } -async fn play_match(selected_bots: Vec, 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(); + for bot in &selected_bots { + let code_bundle = db::bots::active_code_bundle(bot.id, &db_conn) + .expect("could not get active code bundle"); + code_bundles.push(code_bundle); + } + + let code_bundle_refs = code_bundles.iter().map(|b| b).collect::>(); + + let mut run_match = RunMatch::from_players(code_bundle_refs); + run_match + .store_in_database(&db_conn) + .expect("could not store match in db"); + let outcome = run_match + .spawn(db_pool.clone()) + .await + .expect("running match failed"); + + let mut ratings = Vec::new(); + for bot in &selected_bots { + let rating = db::ratings::get_rating(bot.id, &db_conn) + .expect("could not get bot rating") + .unwrap_or(START_RATING); + ratings.push(rating); + } + + // simple elo rating + + let scores = match outcome.winner { + None => vec![0.5; 2], + Some(player_num) => { + // TODO: please get rid of this offset + let player_ix = player_num - 1; + let mut scores = vec![0.0; 2]; + scores[player_ix] = 1.0; + scores + } + }; + + for i in 0..2 { + let j = 1 - i; + + let scaled_difference = (ratings[i] - ratings[j]) / SCALE; + let expected = 1.0 / (1.0 + 10f64.powf(scaled_difference)); + let new_rating = ratings[i] + MAX_UPDATE * (scores[i] - expected); + db::ratings::set_rating(selected_bots[i].id, new_rating, &db_conn) + .expect("could not update bot rating"); + } +} -- cgit v1.2.3 From fadcda850332f8adb0a4382da9f04f78db3f6d1a Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sat, 28 May 2022 11:22:00 +0200 Subject: fix order of arguments in ranker --- planetwars-server/src/modules/ranking.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'planetwars-server/src/modules') diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs index 3892383..cc81f0f 100644 --- a/planetwars-server/src/modules/ranking.rs +++ b/planetwars-server/src/modules/ranking.rs @@ -9,7 +9,7 @@ use tokio; const RANKER_INTERVAL: u64 = 60; const START_RATING: f64 = 0.0; const SCALE: f64 = 100.0; -const MAX_UPDATE: f64 = 5.0; +const MAX_UPDATE: f64 = 10.0; pub async fn run_ranker(db_pool: DbPool) { // TODO: make this configurable @@ -78,7 +78,7 @@ async fn play_ranking_match(selected_bots: Vec, db_pool: DbPool) { for i in 0..2 { let j = 1 - i; - let scaled_difference = (ratings[i] - ratings[j]) / SCALE; + let scaled_difference = (ratings[j] - ratings[i]) / SCALE; let expected = 1.0 / (1.0 + 10f64.powf(scaled_difference)); let new_rating = ratings[i] + MAX_UPDATE * (scores[i] - expected); db::ratings::set_rating(selected_bots[i].id, new_rating, &db_conn) -- cgit v1.2.3