1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
|
extern crate planetwars_matchrunner;
extern crate tokio;
use std::collections::HashMap;
use std::io::{self, Write};
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use bollard::container::{self, LogOutput};
use bollard::exec::StartExecResults;
use bollard::Docker;
use bytes::Bytes;
use futures::{Stream, StreamExt};
use planetwars_matchrunner::{
match_context::{EventBus, MatchCtx, PlayerHandle, RequestMessage},
pw_match, MatchConfig, MatchMeta, PlayerInfo,
};
use planetwars_rules::protocol as proto;
use planetwars_rules::PwConfig;
use std::env;
use tokio::io::{AsyncWrite, AsyncWriteExt};
use tokio::sync::mpsc;
const IMAGE: &'static str = "simplebot:latest";
#[tokio::main]
async fn main() {
let args: Vec<String> = env::args().collect();
assert!(args.len() >= 2);
let map_path = args[1].clone();
_run_match(map_path).await;
}
async fn _run_match(map_path: String) {
let docker = Docker::connect_with_socket_defaults().unwrap();
create_player_process(&docker).await.unwrap();
}
async fn create_player_process(docker: &Docker) -> Result<(), bollard::errors::Error> {
let config = container::Config {
image: Some(IMAGE),
..Default::default()
};
let response = docker.create_container::<&str, &str>(None, config).await?;
let container_id = response.id;
docker
.start_container::<String>(&container_id, None)
.await?;
let exec_id = docker
.create_exec::<&str>(
&container_id,
bollard::exec::CreateExecOptions {
attach_stdin: Some(true),
attach_stdout: Some(true),
attach_stderr: Some(true),
cmd: Some(vec!["python", "simplebot.py"]),
..Default::default()
},
)
.await
.unwrap()
.id;
let start_exec_results = docker.start_exec(&exec_id, None).await?;
let mut process = match start_exec_results {
StartExecResults::Detached => panic!("failed to get io channels"),
StartExecResults::Attached { input, output } => ContainerProcess {
stdin: input,
output,
},
};
let state = proto::State {
planets: vec![
proto::Planet {
name: "a".to_string(),
owner: Some(1),
ship_count: 100,
x: -1.0,
y: 0.0,
},
proto::Planet {
name: "b".to_string(),
owner: Some(2),
ship_count: 100,
x: 1.0,
y: 0.0,
},
],
expeditions: vec![],
};
let serialized = serde_json::to_vec(&state).unwrap();
let out = process.communicate(&serialized).await?;
print!("{}", String::from_utf8(out.to_vec()).unwrap());
Ok(())
}
pub struct ContainerProcess {
stdin: Pin<Box<dyn AsyncWrite + Send>>,
output: Pin<Box<dyn Stream<Item = Result<LogOutput, bollard::errors::Error>>>>,
}
impl ContainerProcess {
pub async fn communicate(&mut self, input: &[u8]) -> io::Result<Bytes> {
self.write_line(input).await?;
self.read_line().await
}
async fn write_line(&mut self, bytes: &[u8]) -> io::Result<()> {
self.stdin.write_all(bytes).await?;
self.stdin.write_u8(b'\n').await?;
self.stdin.flush().await?;
Ok(())
}
async fn read_line(&mut self) -> io::Result<Bytes> {
while let Some(item) = self.output.next().await {
let log_output = item.expect("failed to get log output");
match log_output {
LogOutput::StdOut { message } => {
// TODO: this is not correct (buffering and such)
return Ok(message);
}
LogOutput::StdErr { message } => {
// TODO
println!("stderr: {}", String::from_utf8_lossy(&message));
}
_ => (),
}
}
Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"no response received",
))
}
}
|