-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
279 lines (246 loc) · 8.75 KB
/
main.rs
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
use std::{
env,
error::Error,
fmt, fs,
io::{self, Write},
process::{Command, ExitStatus},
};
use atty::Stream;
use colored::Colorize;
use yaml_rust2::YamlLoader;
enum KubectlCheckError {
KubeconfigIo(io::Error),
KubeconfigParse(yaml_rust2::ScanError),
MalformedKubeconfig,
CurrentContextNotFound(String),
NoCommandSpecified,
NotConfirmed,
CommandFailed(ExitStatus),
}
impl fmt::Display for KubectlCheckError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
KubectlCheckError::KubeconfigIo(ref err) => {
write!(f, "Could not read kubeconfig: {err}")
}
KubectlCheckError::KubeconfigParse(ref err) => {
write!(f, "Could not parse kubeconfig: {err}")
}
KubectlCheckError::NotConfirmed => write!(f, "Execution cancelled."),
KubectlCheckError::CommandFailed(status) => {
write!(f, "{status}")
}
KubectlCheckError::MalformedKubeconfig => write!(f, "Malformed kubeconfig"),
KubectlCheckError::CurrentContextNotFound(current_context) => {
write!(f, "Context not found: {current_context}")
}
KubectlCheckError::NoCommandSpecified => write!(f, "No command for kubectl sepcified"),
}
}
}
impl fmt::Debug for KubectlCheckError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self)
}
}
impl Error for KubectlCheckError {}
type KubectlCheckResult<T> = Result<T, KubectlCheckError>;
fn main() -> KubectlCheckResult<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
if atty::is(Stream::Stdout) {
let kube_config = read_kube_config()?;
let metadata = extract_metadata(kube_config, &args)?;
let unsafe_command_list_env =
env::var("KUBECTL_CHECK_UNSAFE").unwrap_or_else(|_| "".to_string());
let unsafe_command_list = if unsafe_command_list_env.is_empty() {
vec![
"edit", "delete", "rollout", "scale", "cordon", "uncordon", "drain", "taint",
"exec", "create", "apply",
]
} else {
unsafe_command_list_env.split(",").collect()
};
if unsafe_command_list.contains(&metadata.command.as_str()) {
print!(
"Running {} over {}({}) (Y/n): ",
metadata.command.as_str().red().bold(),
metadata.target_context.as_str().green(),
metadata.target_namespace.as_str().green(),
);
io::stdout().flush().expect("could not flush stdout");
let stdin = io::stdin();
let mut buffer = String::new();
if let Err(e) = stdin.read_line(&mut buffer) {
panic!("{}", e);
};
if buffer.trim() != "Y" {
return Err(KubectlCheckError::NotConfirmed);
}
}
}
let mut command = Command::new("kubectl");
command.args(args);
let status = command.status().expect("could not execute kubectl");
if status.success() {
return Ok(());
}
return Err(KubectlCheckError::CommandFailed(status));
}
#[derive(Clone, Debug)]
struct KubeContextMetadata {
namespace: Option<String>,
}
#[derive(Clone, Debug)]
struct KubeContext {
name: String,
context: KubeContextMetadata,
}
#[derive(Clone, Debug)]
struct KubeConfig {
current_context: String,
contexts: Vec<KubeContext>,
}
#[derive(Clone, Debug)]
struct KubectlMetadata {
target_context: String,
target_namespace: String,
command: String,
}
fn get_value(fragment: &str, prefix: &str, iter: &mut std::slice::Iter<String>) -> Option<String> {
if fragment == prefix {
let next_fragment = iter.next();
next_fragment.map(|it| it.to_string())
} else if fragment.starts_with(&format!("{}=", prefix)) {
Some(
fragment
.replace(&format!("{}=", prefix), "")
.trim()
.to_string(),
)
} else {
None
}
}
fn extract_metadata(
kube_config: KubeConfig,
args: &Vec<String>,
) -> KubectlCheckResult<KubectlMetadata> {
let mut context_from_command = None;
let mut namespace_from_command = None;
let mut command = None;
let mut command_iter = args.iter();
while let Some(fragment) = command_iter.next() {
if fragment.starts_with("-") {
if let Some(value) = get_value(fragment, "--context", &mut command_iter) {
context_from_command = Some(value);
}
if let Some(value) = get_value(fragment, "--namespace", &mut command_iter) {
namespace_from_command = Some(value)
}
if let Some(value) = get_value(fragment, "-n", &mut command_iter) {
namespace_from_command = Some(value)
}
} else if command.is_none() {
command = Some(fragment.to_string())
}
}
let target_context = context_from_command.unwrap_or(kube_config.current_context);
let target_namespace = namespace_from_command.unwrap_or(
kube_config
.contexts
.iter()
.find(|&context| context.name == target_context)
.ok_or(KubectlCheckError::CurrentContextNotFound(
target_context.clone(),
))?
.context
.namespace
.clone()
.unwrap_or("default".to_string()),
);
Ok(KubectlMetadata {
target_context,
target_namespace,
command: command.ok_or(KubectlCheckError::NoCommandSpecified)?,
})
}
fn read_kube_config() -> KubectlCheckResult<KubeConfig> {
let path = env::var("KUBECONFIG").unwrap_or(format!(
"{}/.kube/config",
env::var("HOME").unwrap_or("~".to_string())
));
let contents = fs::read_to_string(path).map_err(|err| KubectlCheckError::KubeconfigIo(err))?;
let documents = YamlLoader::load_from_str(&contents)
.map_err(|err| KubectlCheckError::KubeconfigParse(err))?;
let document = &documents[0];
let contexts = &document["contexts"]
.clone()
.into_iter()
.map(|context| {
Ok(KubeContext {
name: context["name"]
.as_str()
.ok_or(KubectlCheckError::MalformedKubeconfig)?
.to_string(),
context: KubeContextMetadata {
namespace: context["context"]["namespace"]
.as_str()
.map(|it| it.to_string()),
},
})
})
.collect::<KubectlCheckResult<Vec<KubeContext>>>()?;
Ok(KubeConfig {
current_context: document["current-context"]
.as_str()
.ok_or(KubectlCheckError::MalformedKubeconfig)?
.to_string(),
contexts: contexts.clone(),
})
}
#[cfg(test)]
mod tests {
mod extract_metadata {
use crate::{extract_metadata, KubeConfig, KubeContext, KubeContextMetadata};
#[test]
fn it_should_get_metadata_scenario_1() {
let kube_config = KubeConfig {
current_context: "context-from-kube-config".to_string(),
contexts: vec![KubeContext {
name: "context-from-command".to_string(),
context: KubeContextMetadata {
namespace: Some("namespace-from-kube-config".to_string()),
},
}],
};
let args = [
"kubectl",
"--context",
"context-from-command",
"get",
"pods",
]
.map(|it| it.to_string())
.to_vec();
let result = extract_metadata(kube_config, &args).unwrap();
assert_eq!(result.target_context, "context-from-command");
assert_eq!(result.target_namespace, "namespace-from-kube-config");
}
#[test]
fn it_should_get_metadata_scenario_2() {
let kube_config = KubeConfig {
current_context: "context-from-kube-config".to_string(),
contexts: vec![KubeContext {
name: "context-from-kube-config".to_string(),
context: KubeContextMetadata {
namespace: Some("namespace-from-kube-config".to_string()),
},
}],
};
let args = ["kubectl", "get", "pods"].map(|it| it.to_string()).to_vec();
let result = extract_metadata(kube_config, &args).unwrap();
assert_eq!(result.target_context, "context-from-kube-config");
assert_eq!(result.target_namespace, "namespace-from-kube-config");
}
}
}