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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! One run: a Job, its pod, the steps, and the result.
//!
//! This is the shape `knotless-run` would call from its executor seam:
//! start a run (the Job), run each step in the same environment, stream
//! the log, copy outputs back, and stop (delete the Job).
use std::fs::{self, File};
use std::io::Write;
use std::path::PathBuf;
use std::process::Stdio;
use std::thread;
use std::time::{Duration, Instant};
use crate::cli::{self, Options};
use crate::json::{option, quote};
use crate::kubectl::Kubectl;
use crate::manifest;
use crate::steps::{self, Step};
/// What one step came to, as `dev.knotless.check` records it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StepResult {
pub name: String,
pub status: String,
pub exit_code: Option<i32>,
pub duration_ms: u128,
pub timed_out: bool,
}
/// The result of one proof-of-concept run.
#[derive(Clone, Debug)]
pub struct Outcome {
pub name: String,
pub job: String,
pub namespace: String,
pub pod: Option<String>,
pub status: String,
pub steps: Vec<StepResult>,
pub log: PathBuf,
pub outputs: Option<PathBuf>,
pub job_deleted: bool,
pub dry_run: bool,
pub error: Option<String>,
}
impl Outcome {
/// Whether the binary should exit zero.
pub fn success(&self) -> bool {
self.dry_run || self.status == "success"
}
/// The result as JSON, the shape a check's steps take.
pub fn to_json(&self) -> String {
let steps: Vec<String> = self
.steps
.iter()
.map(|step| {
format!(
"{{\"name\":{},\"status\":{},\"exitCode\":{},\"durationMs\":{},\"timedOut\":{}}}",
quote(&step.name),
quote(&step.status),
step.exit_code
.map(|code| code.to_string())
.unwrap_or_else(|| "null".to_string()),
step.duration_ms,
step.timed_out
)
})
.collect();
format!(
concat!(
"{{",
"\"name\":{},",
"\"job\":{},",
"\"namespace\":{},",
"\"pod\":{},",
"\"status\":{},",
"\"steps\":[{}],",
"\"log\":{},",
"\"outputs\":{},",
"\"jobDeleted\":{},",
"\"dryRun\":{},",
"\"error\":{}",
"}}"
),
quote(&self.name),
quote(&self.job),
quote(&self.namespace),
option(self.pod.as_deref()),
quote(&self.status),
steps.join(","),
quote(&self.log.display().to_string()),
option(self.outputs.as_ref().map(|p| p.display().to_string()).as_deref()),
self.job_deleted,
self.dry_run,
option(self.error.as_deref())
)
}
}
/// Runs one proof-of-concept workflow.
pub fn run(options: &Options) -> Result<Outcome, String> {
let steps = steps::load(options)?;
let job = manifest::job_name(&options.name)?;
let log_path = cli::log_path(options);
let outputs = options.outputs.clone();
let mut outcome = Outcome {
name: options.name.clone(),
job: job.clone(),
namespace: options.namespace.clone(),
pod: None,
status: "error".to_string(),
steps: Vec::new(),
log: log_path.clone(),
outputs: outputs.clone(),
job_deleted: false,
dry_run: options.dry_run,
error: None,
};
if options.dry_run {
dry_run(options, &job, &steps, &mut outcome)?;
write_result(options, &outcome)?;
return Ok(outcome);
}
let kubectl = Kubectl::new(options);
let manifest = manifest::job_json(options)?;
let mut log = File::create(&log_path)
.map_err(|err| format!("creating {}: {err}", log_path.display()))?;
writeln!(
log,
"==> run {} job {} image {}",
options.name, job, options.image
)
.map_err(|err| format!("writing {}: {err}", log_path.display()))?;
let (created, error) =
match execute(options, &kubectl, &manifest, &job, &steps, &mut log, &mut outcome) {
Ok(created) => (created, None),
Err(err) => (outcome.pod.is_some(), Some(err)),
};
outcome.error = error;
if created && !options.keep {
match kubectl.delete(&job) {
Ok(()) => outcome.job_deleted = true,
Err(err) => {
let _ = writeln!(log, "==> cleanup: {err}");
}
}
} else if options.keep {
let _ = writeln!(log, "==> kept Job {job}");
}
outcome.status = if outcome.error.is_some() {
"error".to_string()
} else if outcome.steps.iter().all(|step| step.status == "success") {
"success".to_string()
} else {
"failure".to_string()
};
let _ = writeln!(log, "==> status {}", outcome.status);
write_result(options, &outcome)?;
Ok(outcome)
}
fn execute(
options: &Options,
kubectl: &Kubectl,
manifest: &str,
job: &str,
steps: &[Step],
log: &mut File,
outcome: &mut Outcome,
) -> Result<bool, String> {
kubectl.apply(manifest)?;
// The Job exists from here on, so cleanup must still find it even if
// the pod never becomes Ready.
outcome.pod = Some(String::new());
if let Err(err) = kubectl.wait_pod(job, options.timeout) {
return Err(err);
}
let pod = kubectl.pod(job)?;
outcome.pod = Some(pod.clone());
kubectl.mkdirs(&pod)?;
kubectl.tar_in(&pod, "/work", &options.workdir)?;
if let Some(steps_dir) = &options.steps_dir {
kubectl.tar_in(&pod, "/steps", steps_dir)?;
}
for (index, step) in steps.iter().enumerate() {
let _ = writeln!(log, "==> step {}: {}", step.name, step.script);
let mut command = kubectl.exec(&pod, &step.script);
command
.stdin(Stdio::null())
.stdout(Stdio::from(log.try_clone().map_err(stringify)?))
.stderr(Stdio::from(log.try_clone().map_err(stringify)?));
let started = Instant::now();
let mut child = match command.spawn() {
Ok(child) => child,
Err(err) => {
outcome.steps.push(StepResult {
name: step.name.clone(),
status: "error".to_string(),
exit_code: None,
duration_ms: started.elapsed().as_millis(),
timed_out: false,
});
skip_rest(steps, index + 1, outcome);
return Err(format!("starting step {}: {err}", step.name));
}
};
let mut exit = None;
let mut timed_out = false;
loop {
match child.try_wait() {
Ok(Some(status)) => {
exit = status.code();
break;
}
Ok(None) => {}
Err(err) => {
outcome.steps.push(StepResult {
name: step.name.clone(),
status: "error".to_string(),
exit_code: None,
duration_ms: started.elapsed().as_millis(),
timed_out: false,
});
skip_rest(steps, index + 1, outcome);
return Err(format!("waiting for step {}: {err}", step.name));
}
}
if started.elapsed() >= options.step_timeout {
let _ = child.kill();
let _ = child.wait();
timed_out = true;
break;
}
thread::sleep(Duration::from_millis(50));
}
let duration_ms = started.elapsed().as_millis();
let status = if timed_out {
"failure"
} else if exit == Some(0) {
"success"
} else {
"failure"
};
let _ = writeln!(
log,
"==> step {} {} exit={:?} in {}ms{}",
step.name,
status,
exit,
duration_ms,
if timed_out { " (timed out)" } else { "" }
);
outcome.steps.push(StepResult {
name: step.name.clone(),
status: status.to_string(),
exit_code: exit,
duration_ms,
timed_out,
});
if timed_out {
skip_rest(steps, index + 1, outcome);
return Ok(true);
}
if exit != Some(0) {
skip_rest(steps, index + 1, outcome);
return Ok(true);
}
}
if let Some(outputs) = &options.outputs {
fs::create_dir_all(outputs)
.map_err(|err| format!("creating {}: {err}", outputs.display()))?;
kubectl.tar_out(&pod, "/outputs", outputs)?;
}
Ok(true)
}
fn skip_rest(steps: &[Step], from: usize, outcome: &mut Outcome) {
for step in &steps[from..] {
outcome.steps.push(StepResult {
name: step.name.clone(),
status: "skipped".to_string(),
exit_code: None,
duration_ms: 0,
timed_out: false,
});
}
}
fn dry_run(
options: &Options,
job: &str,
steps: &[Step],
outcome: &mut Outcome,
) -> Result<(), String> {
let kubectl = Kubectl::new(options);
println!("{}", manifest::job_json(options)?);
println!("# {}", kubectl.planned(&["apply", "-f", "-"]));
println!(
"# {}",
kubectl.planned(&[
"wait",
"--for=condition=Ready",
"pod",
"-l",
&format!("job-name={job}"),
"--timeout",
&format!("{}s", options.timeout.as_secs()),
])
);
println!(
"# {}",
kubectl.planned(&[
"get",
"pods",
"-l",
&format!("job-name={job}"),
"-o",
"jsonpath={.items[0].metadata.name}",
])
);
println!(
"# {}",
kubectl.planned(&["exec", "<pod>", "--", "mkdir", "-p", "/work", "/outputs", "/steps"])
);
println!("# tar -cf - -C {} . | {}", options.workdir.display(), kubectl.planned(&["exec", "-i", "<pod>", "--", "tar", "-xf", "-", "-C", "/work"]));
if let Some(steps_dir) = &options.steps_dir {
println!("# tar -cf - -C {} . | {}", steps_dir.display(), kubectl.planned(&["exec", "-i", "<pod>", "--", "tar", "-xf", "-", "-C", "/steps"]));
}
for step in steps {
println!("# {}", kubectl.planned(&["exec", "<pod>", "--", "sh", "-ec", &step.script]));
outcome.steps.push(StepResult {
name: step.name.clone(),
status: "skipped".to_string(),
exit_code: None,
duration_ms: 0,
timed_out: false,
});
}
if let Some(outputs) = &options.outputs {
println!("# {} | tar -xf - -C {}", kubectl.planned(&["exec", "<pod>", "--", "tar", "-cf", "-", "-C", "/outputs", "."]), outputs.display());
}
if !options.keep {
println!("# {}", kubectl.planned(&["delete", "job", job, "--ignore-not-found", "--wait=false"]));
}
outcome.status = "dry-run".to_string();
Ok(())
}
fn write_result(options: &Options, outcome: &Outcome) -> Result<(), String> {
let json = outcome.to_json();
match &options.result {
Some(path) => fs::write(path, format!("{json}\n"))
.map_err(|err| format!("writing {}: {err}", path.display())),
None => {
println!("{json}");
Ok(())
}
}
}
fn stringify(err: std::io::Error) -> String {
err.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn result_json() {
let outcome = Outcome {
name: "ci 1".into(),
job: "ci-1".into(),
namespace: "default".into(),
pod: Some("pod-1".into()),
status: "failure".into(),
steps: vec![StepResult {
name: "test".into(),
status: "failure".into(),
exit_code: Some(1),
duration_ms: 12,
timed_out: false,
}],
log: PathBuf::from("ci.log"),
outputs: None,
job_deleted: true,
dry_run: false,
error: None,
};
let json = outcome.to_json();
assert!(json.contains("\"name\":\"ci 1\""));
assert!(json.contains("\"exitCode\":1"));
assert!(json.contains("\"outputs\":null"));
assert!(json.contains("\"jobDeleted\":true"));
}
}