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
//! The `kubectl` calls the proof of concept makes.
//!
//! The real executor would use a Kubernetes client crate. The proof of
//! concept shells out to `kubectl` for the same reason knotless's docker
//! executor shells out to `docker`: the transport is visible, and a fake
//! client in the tests can show every call.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use crate::cli::Options;
/// A configured `kubectl` client.
#[derive(Clone, Debug)]
pub struct Kubectl {
program: PathBuf,
kubeconfig: Option<PathBuf>,
context: Option<String>,
namespace: String,
}
impl Kubectl {
pub fn new(options: &Options) -> Self {
Self {
program: options.kubectl.clone(),
kubeconfig: options.kubeconfig.clone(),
context: options.context.clone(),
namespace: options.namespace.clone(),
}
}
/// The client with its kubeconfig, context and namespace.
fn base(&self) -> Command {
let mut command = Command::new(&self.program);
if let Some(kubeconfig) = &self.kubeconfig {
command.arg("--kubeconfig").arg(kubeconfig);
}
if let Some(context) = &self.context {
command.arg("--context").arg(context);
}
command.args(["-n", &self.namespace]);
command
}
/// A readable line for `--dry-run`, as a shell would take it.
pub fn planned(&self, args: &[&str]) -> String {
let mut parts = vec![self.program.display().to_string()];
if let Some(kubeconfig) = &self.kubeconfig {
parts.push("--kubeconfig".into());
parts.push(kubeconfig.display().to_string());
}
if let Some(context) = &self.context {
parts.push("--context".into());
parts.push(context.clone());
}
parts.push("-n".into());
parts.push(self.namespace.clone());
parts.extend(args.iter().map(|a| shell_word(a)));
parts.join(" ")
}
/// Applies the Job manifest from stdin.
pub fn apply(&self, manifest: &str) -> Result<(), String> {
let mut child = self
.base()
.args(["apply", "-f", "-"])
.stdin(Stdio::piped())
.spawn()
.map_err(|err| format!("running {}: {err}", self.program.display()))?;
{
let mut stdin = child
.stdin
.take()
.ok_or_else(|| "kubectl apply: no stdin".to_string())?;
stdin
.write_all(manifest.as_bytes())
.map_err(|err| format!("writing the Job manifest: {err}"))?;
}
let status = child
.wait()
.map_err(|err| format!("waiting for kubectl apply: {err}"))?;
if !status.success() {
return Err("kubectl apply failed".to_string());
}
Ok(())
}
/// Waits for the Job's pod to be Ready.
pub fn wait_pod(&self, job: &str, timeout: Duration) -> Result<(), String> {
let selector = format!("job-name={job}");
let timeout = format!("{}s", timeout.as_secs().max(1));
let status = self
.base()
.args([
"wait",
"--for=condition=Ready",
"pod",
"-l",
&selector,
"--timeout",
&timeout,
])
.status()
.map_err(|err| format!("running kubectl wait: {err}"))?;
if !status.success() {
return Err(format!("pod for Job {job} did not become Ready"));
}
Ok(())
}
/// The first pod of the Job.
pub fn pod(&self, job: &str) -> Result<String, String> {
let selector = format!("job-name={job}");
let output = self
.base()
.args([
"get",
"pods",
"-l",
&selector,
"-o",
"jsonpath={.items[0].metadata.name}",
])
.output()
.map_err(|err| format!("running kubectl get pods: {err}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("kubectl get pods failed: {}", stderr.trim()));
}
let pod = String::from_utf8_lossy(&output.stdout).trim().to_string();
if pod.is_empty() {
return Err(format!("Job {job} has no pod"));
}
Ok(pod)
}
/// The command that runs `script` in `pod` as a step.
pub fn exec(&self, pod: &str, script: &str) -> Command {
let mut command = self.base();
command.args(["exec", pod, "--", "sh", "-ec", script]);
command
}
/// Makes the directories the run streams into.
pub fn mkdirs(&self, pod: &str) -> Result<(), String> {
let status = self
.base()
.args(["exec", pod, "--", "mkdir", "-p", "/work", "/outputs", "/steps"])
.status()
.map_err(|err| format!("running kubectl exec mkdir: {err}"))?;
if !status.success() {
return Err("creating /work, /outputs and /steps in the pod failed".to_string());
}
Ok(())
}
/// Streams the contents of `source` on this host into `dest` in `pod`,
/// over `kubectl exec -i` and tar, which Kubernetes has in place of a
/// file copy API.
pub fn tar_in(&self, pod: &str, dest: &str, source: &Path) -> Result<(), String> {
let mut tar = Command::new("tar")
.args(["-cf", "-", "-C"])
.arg(source)
.arg(".")
.stdout(Stdio::piped())
.spawn()
.map_err(|err| format!("running tar for {}: {err}", source.display()))?;
let stdout = tar
.stdout
.take()
.ok_or_else(|| "tar: no stdout".to_string())?;
let mut kubectl = self.base();
kubectl
.args(["exec", "-i", pod, "--", "tar", "-xf", "-", "-C", dest])
.stdin(Stdio::from(stdout))
.stdout(Stdio::null());
let status = wait(
kubectl
.spawn()
.map_err(|err| format!("running kubectl exec tar: {err}"))?,
"kubectl exec tar",
)?;
let tar_status = wait(tar, "tar")?;
if !status.success() {
return Err(format!(
"streaming {} into {dest} failed",
source.display()
));
}
if !tar_status.success() {
return Err(format!("tar reading {} failed", source.display()));
}
Ok(())
}
/// Streams the contents of `source` in `pod` into `dest` on this host.
pub fn tar_out(&self, pod: &str, source: &str, dest: &Path) -> Result<(), String> {
let mut kubectl = self.base();
kubectl
.args(["exec", pod, "--", "tar", "-cf", "-", "-C", source, "."])
.stdout(Stdio::piped());
let mut kubectl = kubectl
.spawn()
.map_err(|err| format!("running kubectl exec tar: {err}"))?;
let stdout = kubectl
.stdout
.take()
.ok_or_else(|| "kubectl exec tar: no stdout".to_string())?;
let tar = Command::new("tar")
.args(["-xf", "-", "-C"])
.arg(dest)
.stdin(Stdio::from(stdout))
.spawn()
.map_err(|err| format!("running tar for {}: {err}", dest.display()))?;
let status = wait(kubectl, "kubectl exec tar")?;
let tar_status = wait(tar, "tar")?;
if !status.success() {
return Err(format!("streaming {source} out of the pod failed"));
}
if !tar_status.success() {
return Err(format!("tar writing {} failed", dest.display()));
}
Ok(())
}
/// Deletes the Job and its pod. Missing is fine.
pub fn delete(&self, job: &str) -> Result<(), String> {
let status = self
.base()
.args(["delete", "job", job, "--ignore-not-found", "--wait=false"])
.status()
.map_err(|err| format!("running kubectl delete: {err}"))?;
if !status.success() {
return Err(format!("kubectl delete job {job} failed"));
}
Ok(())
}
}
fn wait(mut child: Child, what: &str) -> Result<std::process::ExitStatus, String> {
child
.wait()
.map_err(|err| format!("waiting for {what}: {err}"))
}
/// A shell-ish word for a dry-run line, quoted only when it has spaces.
fn shell_word(word: &str) -> String {
if word.is_empty()
|| word
.chars()
.any(|c| c.is_whitespace() || matches!(c, '\'' | '"' | '$' | '`' | '\\'))
{
format!("'{}'", word.replace('\'', "'\\''"))
} else {
word.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn client() -> Kubectl {
Kubectl {
program: PathBuf::from("kubectl"),
kubeconfig: Some(PathBuf::from("/k")),
context: Some("ctx".into()),
namespace: "ci".into(),
}
}
#[test]
fn plans() {
assert_eq!(
client().planned(&["exec", "pod", "--", "sh", "-ec", "echo hi"]),
"kubectl --kubeconfig /k --context ctx -n ci exec pod -- sh -ec 'echo hi'"
);
}
#[test]
fn exec_args() {
let command = client().exec("pod-1", "make test");
let args: Vec<_> = command.get_args().map(|a| a.to_string_lossy()).collect();
assert_eq!(
args,
vec![
"--kubeconfig",
"/k",
"--context",
"ctx",
"-n",
"ci",
"exec",
"pod-1",
"--",
"sh",
"-ec",
"make test"
]
);
}
}