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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use super::*;
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct Job {
pub(crate) script: String,
name: String,
pub out_file: PathBuf,
pub err_file: PathBuf,
pub run_file: PathBuf,
}
impl Default for Job {
fn default() -> Self {
Self {
script: "pwd".into(),
name: random_name(),
out_file: "job.out".into(),
err_file: "job.err".into(),
run_file: "run".into(),
}
}
}
impl Job {
pub fn new(script: impl Into<String>) -> Self {
Self {
script: script.into(),
..Default::default()
}
}
pub fn with_name(mut self, name: &str) -> Self {
self.name = name.into();
self
}
pub fn name(&self) -> String {
self.name.clone()
}
}
fn random_name() -> String {
use rand::distributions::Alphanumeric;
use rand::Rng;
let mut rng = rand::thread_rng();
std::iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.map(char::from)
.take(6)
.collect()
}
mod node {
use super::*;
use crossbeam_channel::{unbounded, Receiver, Sender};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Node {
name: String,
}
impl Node {
pub fn name(&self) -> &str {
&self.name
}
}
impl<T: Into<String>> From<T> for Node {
fn from(node: T) -> Self {
let name = node.into();
assert!(!name.is_empty(), "node name cannot be empty!");
Self { name }
}
}
impl std::fmt::Display for Node {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let name = &self.name;
write!(f, "{name}")
}
}
#[derive(Clone)]
pub struct Nodes {
rx: Receiver<Node>,
tx: Sender<Node>,
}
impl Nodes {
pub fn new<T: Into<Node>>(nodes: impl IntoIterator<Item = T>) -> Self {
let (tx, rx) = unbounded();
let nodes = nodes.into_iter().collect_vec();
let n = nodes.len();
info!("We have {n} nodes in totoal for computation.");
for node in nodes {
tx.send(node.into()).unwrap();
}
Self { rx, tx }
}
pub fn len(&self) -> usize {
self.rx.len()
}
pub fn borrow_node(&self) -> Result<Node> {
let node = self.rx.recv()?;
let name = &node.name;
info!("client borrowed one node: {name:?}");
Ok(node)
}
pub fn return_node(&self, node: Node) -> Result<()> {
let name = &node.name;
info!("client returned node {name:?}");
self.tx.send(node)?;
Ok(())
}
}
}
use std::path::{Path, PathBuf};
use gosh_runner::prelude::SpawnSessionExt;
use gosh_runner::process::Session;
use tempfile::TempDir;
pub struct Computation {
job: Job,
session: Option<Session<tokio::process::Child>>,
wrk_dir: TempDir,
}
impl Computation {
fn wrk_dir(&self) -> &Path {
self.wrk_dir.path()
}
fn out_file(&self) -> PathBuf {
self.wrk_dir().join(&self.job.out_file)
}
fn err_file(&self) -> PathBuf {
self.wrk_dir().join(&self.job.err_file)
}
fn run_file(&self) -> PathBuf {
self.wrk_dir().join(&self.job.run_file)
}
}
impl Job {
pub fn submit(self) -> Result<Computation> {
Computation::try_run(self)
}
}
impl Computation {
fn create_run_file(&self) -> Result<()> {
let run_file = &self.run_file();
gut::fs::write_script_file(run_file, &self.job.script)?;
LockFile::wait(&run_file, 2.0)?;
Ok(())
}
fn try_run(job: Job) -> Result<Self> {
let wdir = tempfile::TempDir::new_in(".").expect("temp dir");
let session = Self {
job,
wrk_dir: wdir.into(),
session: None,
};
session.create_run_file()?;
Ok(session)
}
async fn wait(&mut self) -> Result<()> {
if let Some(s) = self.session.as_mut() {
let ecode = s.child.wait().await?;
info!("job session exited: {}", ecode);
if !ecode.success() {
error!("job exited unsuccessfully!");
let txt = gut::fs::read_file(self.run_file())?;
let run = format!("run file: {txt:?}");
let txt = gut::fs::read_file(self.err_file())?;
let err = format!("stderr: {txt:?}");
bail!("Job failed with error:\n{run:?}{err:?}");
}
Ok(())
} else {
bail!("Job not started yet.");
}
}
async fn start(&mut self) -> Result<()> {
let program = self.run_file();
let wdir = self.wrk_dir();
trace!("job work direcotry: {}", wdir.display());
let mut session = tokio::process::Command::new(&program)
.current_dir(wdir)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn_session()?;
let mut stdout = session
.child
.stdout
.take()
.expect("child did not have a handle to stdout");
let mut stderr = session
.child
.stderr
.take()
.expect("child did not have a handle to stderr");
let mut fout = tokio::fs::File::create(self.out_file()).await?;
let mut ferr = tokio::fs::File::create(self.err_file()).await?;
tokio::io::copy(&mut stdout, &mut fout).await?;
tokio::io::copy(&mut stderr, &mut ferr).await?;
let sid = session.handler().id();
debug!("command running in session {:?}", sid);
self.session = session.into();
Ok(())
}
pub async fn wait_for_output(&mut self) -> Result<String> {
self.start().await?;
self.wait().await?;
let txt = gut::fs::read_file(self.out_file())?;
Ok(txt)
}
}
#[derive(Debug)]
pub struct LockFile {
file: std::fs::File,
path: PathBuf,
}
impl LockFile {
fn create(path: &Path) -> Result<LockFile> {
use fs2::*;
let file = std::fs::OpenOptions::new()
.create(true)
.write(true)
.open(&path)
.context("Could not create ID file")?;
file.try_lock_exclusive()
.context("Could not lock lock file; Is the instance already running?")?;
Ok(LockFile {
file,
path: path.to_owned(),
})
}
fn write_msg(&mut self, msg: &str) -> Result<()> {
writeln!(&mut self.file, "{msg}").context("Could not write lock file")?;
self.file.flush().context("Could not flush lock file")
}
pub fn new(path: &Path, msg: impl std::fmt::Display) -> Result<Self> {
let mut lockfile = Self::create(path)?;
lockfile.write_msg(&msg.to_string())?;
Ok(lockfile)
}
pub fn wait(f: &std::path::Path, timeout: f64) -> Result<()> {
use gut::utils::sleep;
let interval = 0.1;
let mut t = 0.0;
loop {
if f.exists() {
trace!("Elapsed time during waiting: {:.2} seconds ", t);
return Ok(());
}
t += interval;
sleep(interval);
if t > timeout {
bail!("file {:?} doest exist for {} seconds", f, timeout);
}
}
}
}
impl Drop for LockFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
pub use node::{Node, Nodes};
#[test]
fn test_node() {
let localhost: Node = "localhost".into();
assert_eq!(localhost.name(), "localhost");
}